code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package org.annoflow.javassist;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The Class Macro. This abstract class represents a macro defined in a
* configuration file. Note, all parameters in the macro body must be prefixed
* by a %.
*
* define <Macro Name>(<Parameters>) <Macro Body>
*
* The macros are then used in other command bodies like so:
*
* %<MacroName>(<Parameters>)
*
*
*
*/
public abstract class Macro
{
public class MalformedMacroParametersException extends
MalformedMacroException
{
/**
*
*/
private static final long serialVersionUID = 1L;
public MalformedMacroParametersException(String macro)
{
super("Unable to parse parameters in " + macro);
}
}
/** The macro. */
String macro;
/** The macro name. */
String macroName;
/** The macro params. */
List<String> macroParams;
/** The macro name pat. */
Pattern macroNamePat;
/** The param pat. */
Pattern paramPat;
/**
* Instantiates a new macro. This constructor allows a user to define a
* custom patter for parameters and names.
*
* @param userMacro
* the name of the user passed macro
* @param namePattern
* the pattern used to identify the name
* @param paramPattern
* the the pattern used to identify the parameters.
*
* @throws MalformedMacroParametersException
* the malformed macro parameters exception
*/
public Macro(String userMacro, String namePattern, String paramPattern)
throws MalformedMacroException
{
macroNamePat = Pattern.compile(namePattern);
paramPat = Pattern.compile(paramPattern);
macro = userMacro;
macroName = getMacroName(macro);
macroParams = getParameters(macro);
}
/**
* Gets the number of parameters this macro requries.
*
* @return the number of params
*/
public int getNumberOfParams()
{
return macroParams.size();
}
/**
* Gets the macro name.
*
* @return the macro name
*/
public String getMacroName()
{
return macroName;
}
/**
* Gets the parameter iterator.
*
* @return the parameter iterator
*/
public Iterator<String> getParameterIterator()
{
return macroParams.iterator();
}
private String getMacroName(String macro) throws MalformedMacroException
{
String mName = "";
Matcher macroNameMatcher = macroNamePat.matcher(macro);
// Matcher parameterMatcher = parameter.matcher(macro);
if (macroNameMatcher.find())
{
mName = macroNameMatcher.group().substring(0,
macroNameMatcher.end() - 1);
macro = macro.substring(macroNameMatcher.end());
// System.out.println(m.group());
}
else
{
System.err.println("Malformed Macro");
throw new MalformedMacroException("Unable to find macro name in: "
+ macro);
}
return mName;
}
private List<String> getParameters(String macro)
throws MalformedMacroParametersException
{
List<String> parameters = new ArrayList<String>();
// Pattern paramPat = Pattern.compile("\\(.*\\)\\s*\\{");
Matcher parameterSectionMatcher = paramPat.matcher(macro);
String parameterSection = "";
if (parameterSectionMatcher.find())
{
parameterSection = parameterSectionMatcher.group();
}
else
{
throw new MalformedMacroParametersException(macro);
}
// Pattern parameter = Pattern.compile("[^(%),.\\s]+[,|\\)]");
parameterSection = parameterSection.trim().substring(1);
Pattern parameter = Pattern.compile("[^\\s]+\\s*,");
Matcher parameterMatcher = parameter.matcher(parameterSection);
while (parameterMatcher.find())
{
String tempParam = parameterMatcher.group().trim();
tempParam = tempParam.substring(0, tempParam.length() - 1);
parameterSection = parameterSection.substring(
parameterMatcher.end()).trim();
parameterMatcher = parameter.matcher(parameterSection);
parameters.add(tempParam);
}
Pattern lastParam = Pattern.compile("[^\\s]+\\s*\\)");
Matcher lastParamMatch = lastParam.matcher(parameterSection);
if (lastParamMatch.find())
{
String lParam = lastParamMatch.group();
lParam = lParam.trim().substring(0, lParam.length() - 1);
lParam = lParam.trim();
parameters.add(lParam);
}
return parameters;
}
}
| Java |
package org.annoflow.javassist;
import java.util.List;
import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.expr.Expr;
import javassist.expr.Handler;
import org.annoflow.javassist.AbstractCommand.CommandNotImplementedException;
import org.annoflow.javassist.AbstractCommand.SignatureType;
import org.apache.log4j.Logger;
/**
* The Class InsertBefore. This class is used to represent an insert before
* command. It is used to limit the types of expressions and methods that can be
* translated.
*
* translate InsertBefore <Class Name> <Method name> <Source body>
*
*/
public class InsertBefore implements CommandInterface
{
private Logger logger = Logger.getLogger(InsertBefore.class);
private List<String> configArgs;
/**
* Instantiates a new insert before command.
*
* @param args
* the args
*
* @throws MalformedCommandException
* the malformed command exception
*/
public InsertBefore(List<String> args) throws MalformedCommandException
{
configArgs = args;
}
public void translate(Expr call, boolean isSuper)
throws MalformedCommandException, CannotCompileException
{
if (call instanceof Handler)
{
translate((Handler) call);
return;
}
throw new MalformedCommandException(
"This command is not implemented for the parameters passed");
}
/*
* (non-Javadoc)
*
* @see cloudspace.vm.javassist.commands.CommandInterface#translate
* (javassist.CtMethod, java.lang.String)
*/
@Override
public void translate(CtMethod member, String expressionName)
throws MalformedCommandException, CannotCompileException,
CommandNotImplementedException
{
throw new MalformedCommandException(
"This command is not implemented for the parameters passed");
}
/**
* Translate.
*
* @param call
* the call
*
* @throws MalformedCommandException
* the malformed command exception
* @throws CannotCompileException
* the cannot compile exception
*/
public void translate(Handler call) throws MalformedCommandException,
CannotCompileException
{
// String signature;
//
// signature = getSignature();
call.insertBefore(getReplacement());
}
@Override
public String getReplacement()
{
return configArgs.get(3).substring(1, configArgs.get(3).length() - 1);
}
@Override
public String getSignature()
{
return configArgs.get(1);
}
@Override
public SignatureType getSignatureType()
{
return SignatureType.STATICDEFINITION;
}
@Override
public void translate(CtClass clazz) throws MalformedCommandException,
CannotCompileException
{
CtClass superClazz;
try
{
CtMethod[] meths = clazz.getDeclaredMethods();
superClazz = clazz.getSuperclass();
while (superClazz != null)
{
if (superClazz.getName().equals(getSignature()))
{
for (CtMethod meth : meths)
{
if (meth.getName().endsWith(configArgs.get(2)))
meth.insertBefore(getReplacement());
}
}
superClazz = superClazz.getSuperclass();
}
}
catch (NotFoundException e)
{
logger.error("Method to translate not found",e);
;
}
}
}
| Java |
package org.annoflow.javassist;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
/**
* A factory for creating Command objects. This factory takes a command provided
* in a javassist configuration file and produces a command.
*/
public class CommandFactory
{
private static final String CLOUDSPACE_VM_JAVASSIST = "org.annoflow.javassist.";
private static Logger logger = Logger.getLogger(CommandFactory.class);
/** The macro hash. */
public static HashMap<String, MacroDefinition> macroHash = new HashMap<String, MacroDefinition>();
/**
* Creates a command object from a list of arguments parsed from the command
* line.
*
* @param args
* the arguments parsed out of a javassist configuration file
*
* @return the created command
*
* @throws MalformedCommandException
* the malformed command exception
* @throws MalformedMacroException
* the malformed macro exception
*/
public static CommandInterface createCommand(List<String> args)
throws MalformedCommandException, MalformedMacroException
{
cleanArgs(args);
String commandType = args.get(0);
String command = args.get(args.size() - 1);
Pattern macroPattern = Pattern.compile("%[a-zA-z0-9]+\\([^\\)]*\\)");
Matcher macros = macroPattern.matcher(command);
// Find Macros in the replacement text
while (macros.find())
{
String inlineMacro = macros.group();
macros = macroPattern.matcher(command.substring(macros.end()));
MacroCall inline = new MacroCall(inlineMacro);
MacroDefinition definition = macroHash.get(inline.getMacroName());
if (definition == null)
{
throw new MalformedMacroException("The macro call, "
+ inline.getMacroName()
+ ", does not match any known definitions");
}
String replacement = definition.getTailoredCommand(inline);
String fixedCommand = command.replace(inlineMacro, replacement);
args.set(args.size() - 1, fixedCommand);
}
try
{
Class<?> clazz = Class.forName(CLOUDSPACE_VM_JAVASSIST
+ commandType);
Constructor<?> constr = clazz
.getDeclaredConstructor(new Class<?>[] { java.util.List.class });
CommandInterface reflectCommand = (CommandInterface) constr
.newInstance(new Object[] { args });
return reflectCommand;
}
catch (Exception e)
{
logger.error("The command " + commandType
+ " does not have a matching command class.",e);
}
throw new MalformedCommandException("The translationType " + command
+ " is unknown in command: " + args.toString());
}
/**
* this cleans an argument list to remove arguments that are known to add no
* meaning to a command.
*
* @param args
* the args
*/
private static void cleanArgs(List<String> args)
{
args.remove("with");
}
/**
* Registers a macro to the command factory. The macros are automatically
* used when creating commands to create clean commands without macro
* references in them.
*
* @param curMacro
* the cur macro
*/
public static void registerMacro(MacroDefinition curMacro)
{
macroHash.put(curMacro.getMacroName(), curMacro);
}
}
| Java |
package org.annoflow.javassist;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.NotFoundException;
import org.apache.log4j.Logger;
/**
* The Class ConfigParser. This class is responsible for parsing configurations.
* The config parser will parse a configuration file once. this config parser
* should be kept as a wrapper for the configuration file. The parser will
* automatically update if the underlying configurationfile has been updated.
*/
public class ConfigParser
{
/** The time stamp. */
private long timeStamp;
/** The config file. */
private File configFile;
/** The expr editors. */
private List<CommandInterface> exprEditors;
private Map<String, CtClass> customClasses;
/** The start command. */
Pattern startCommand;
private ClassPool proxyPool;
private Logger logger = Logger.getLogger(ConfigParser.class);
/**
* Instantiates a new config parser.
*
* @param file
* the file to use as a backend configuration.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public ConfigParser(File file, ClassPool pPool) throws IOException
{
proxyPool = pPool;
customClasses = new HashMap<String, CtClass>();
startCommand = Pattern
.compile("replace|insertAfter|insertBefore|define");
configFile = file;
timeStamp = configFile.lastModified();
if (timeStamp == 0)
{
throw new FileNotFoundException();
}
parseEditors();
}
/**
* This will look for updates to the configuration file and automatically
* update the editors underneath
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public void autoUpdate() throws IOException
{
if (timeStamp != configFile.lastModified())
{
parseEditors();
timeStamp = configFile.lastModified();
}
}
private String grepUntillEOC(Scanner confScanner, String EOC)
{
Pattern endOfCommand = Pattern.compile(EOC);
String fullCommand = "";
while (confScanner.hasNext() && !confScanner.hasNext(endOfCommand))
{
String commandPart = confScanner.next();
fullCommand += " ";
fullCommand += commandPart;
}
confScanner.next();
return fullCommand;
}
private void parseEditors() throws IOException
{
Pattern comment = Pattern.compile("^//.*");
Pattern translationType = Pattern.compile("translate");
Pattern macroType = Pattern.compile("define");
Pattern proxyType = Pattern.compile("proxy");
exprEditors = new ArrayList<CommandInterface>();
FileReader inputStream = new FileReader(configFile);
Scanner configScanner = new Scanner(inputStream);
while (configScanner.hasNext())
{
if (configScanner.hasNext(comment))
{
configScanner.nextLine();
continue;
}
else if (configScanner.hasNext(translationType))
{
configScanner.next();
createCommand(configScanner);
}
else if (configScanner.hasNext(macroType))
{
try
{
MacroDefinition curMacro = createMacro(configScanner);
CommandFactory.registerMacro(curMacro);
}
catch (MalformedMacroException e)
{
logger.error("Bad Macro",e);
}
}
else if (configScanner.hasNext(proxyType))
{
createProxy(configScanner);
}
else
{
configScanner.next();
}
}
}
private void createProxy(Scanner configScanner)
{
configScanner.next();
String proxyClass = configScanner.next();
int lastAccessor = proxyClass.lastIndexOf('.');
String newClassName = "auto.generated._"
+ proxyClass.substring(lastAccessor + 1);
CtClass pClass = proxyPool.makeClass(newClassName);
try
{
CtClass actualClass = proxyPool.get(proxyClass);
CtMethod[] methods = actualClass.getMethods();
CtConstructor[] constructors = actualClass.getConstructors();
for (CtConstructor constr : constructors)
{
if (Modifier.isPublic(constr.getModifiers()))
{
CtClass[] paramTypes = constr.getParameterTypes();
String methodSig = "public static " + actualClass.getName()
+ " _constructor(";
int argNum = 0;
for (CtClass param : paramTypes)
{
methodSig += param.getName();
methodSig += " arg" + argNum;
methodSig += ",";
argNum++;
}
if (paramTypes.length != 0)
methodSig = methodSig.substring(0,
methodSig.length() - 1);
methodSig += ")";
CtClass[] execeptionTypes = constr.getExceptionTypes();
if (execeptionTypes.length != 0)
{
methodSig += " throws ";
}
for (CtClass exception : execeptionTypes)
{
methodSig += exception.getName() + ",";
}
if (execeptionTypes.length != 0)
methodSig = methodSig.substring(0,
methodSig.length() - 1);
methodSig += "{return new " + actualClass.getName() + "(";
for (int i = 0; i < paramTypes.length; i++)
{
methodSig += "arg" + i;
if (i < paramTypes.length - 1)
methodSig += ",";
}
methodSig += ");}";
try
{
CtMethod proxyMethod = CtNewMethod.make(methodSig,
pClass);
pClass.addMethod(proxyMethod);
}
catch (CannotCompileException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for (CtMethod method : methods)
{
if (Modifier.isPublic(method.getModifiers()))
{
String methodName = method.getName();
String returnType = method.getReturnType().getName();
CtClass[] paramTypes = method.getParameterTypes();
String methodSig = "public static " + returnType + " _"
+ methodName + "(";
int argNum = 0;
if (!Modifier.isStatic(method.getModifiers()))
{
methodSig += proxyClass + " arg0";
if (paramTypes.length != 0)
{
methodSig += ",";
}
argNum++;
}
for (int i = 0; i < paramTypes.length; i++)
{
methodSig += paramTypes[i].getName();
methodSig += " arg" + argNum;
argNum++;
if (i + 1 < paramTypes.length)
{
methodSig += ",";
}
}
methodSig += ")";
CtClass[] execeptionTypes = method.getExceptionTypes();
if (execeptionTypes.length != 0)
{
methodSig += " throws ";
}
for (CtClass exception : execeptionTypes)
{
methodSig += exception.getName() + ",";
}
if (execeptionTypes.length != 0)
methodSig = methodSig.substring(0,
methodSig.length() - 1);
methodSig += "{";
if (!returnType.equals("void"))
methodSig += "return ";
argNum = 0;
if (Modifier.isStatic(method.getModifiers()))
{
methodSig += actualClass.getName() + "." + methodName
+ "(";
}
else
{
methodSig += "arg" + argNum + "." + methodName + "(";
argNum++;
}
for (int i = 0; i < paramTypes.length; i++)
{
methodSig += "arg" + argNum;
if (i + 1 < paramTypes.length)
methodSig += ",";
argNum++;
}
methodSig += ");}";
try
{
CtMethod proxyMethod = CtNewMethod.make(methodSig,
pClass);
pClass.addMethod(proxyMethod);
}
catch (CannotCompileException e)
{
logger.error("Cannot Compile the new method for: "+method.getName(),e);
}
}
}
}
catch (NotFoundException e)
{
logger.error("Could not find class for proxy",e);
}
customClasses.put(proxyClass, pClass);
}
private MacroDefinition createMacro(Scanner configScanner)
throws MalformedMacroException
{
configScanner.next();
String macro = configScanner.nextLine().trim();
Pattern quotePat = Pattern.compile("\\<\\<\\s+[a-zA-Z0-9]+");
String quotation = null;
Matcher quoteMatch = quotePat.matcher(macro);
if (quoteMatch.find())
{
quotation = quoteMatch.group();
}
if (quotation != null)
{
String commandPart = macro.substring(
macro.indexOf(quotation) + quotation.length()).trim();
macro = macro.substring(0, macro.indexOf(quotation)).trim() + " \"";
quotation = quotation.substring(2).trim();
// Pattern endOfCommandPattern = Pattern.compile(quotation);
if (commandPart.contains(quotation))
{
commandPart = commandPart.substring(0, commandPart
.indexOf(quotation));
}
else
{
commandPart += grepUntillEOC(configScanner, quotation) + "\"";
/*
* while(!configScanner.hasNext(endOfCommandPattern)) {
* commandPart += configScanner.next(); } configScanner.next();
* }
*/
macro += " " + commandPart;
}
}
MacroDefinition curMacro = new MacroDefinition(macro);
return curMacro;
}
private void createCommand(Scanner configScanner)
{
Pattern beginOfCommand = Pattern.compile("<<|\\\".*");
List<String> args = new ArrayList<String>();
boolean end = false;
while (configScanner.hasNext() && !end)
{
while (!configScanner.hasNext(beginOfCommand))
{
args.add(configScanner.next());
}
if (configScanner.hasNext(beginOfCommand))
{
if (configScanner.hasNext("\\\".*"))
{
String commandSection = configScanner.nextLine();
commandSection = commandSection.trim();
args.add(commandSection);
end = true;
}
else if (configScanner.hasNext("<<"))
{
configScanner.next();
String commandEnd = configScanner.next();
String fullCommand = "\""
+ grepUntillEOC(configScanner, commandEnd) + "\"";
args.add(fullCommand);
end = true;
}
}
else
{
String fullCommand = configScanner.nextLine();
args.add(fullCommand);
end = true;
}
}
try
{
CommandInterface curCommand = CommandFactory.createCommand(args);
exprEditors.add(curCommand);
}
catch (MalformedCommandException e)
{
logger.error("Bad command: " + args,e);
}
catch (MalformedMacroException e)
{
logger.error("Bad Macro: " + args, e);
}
}
/**
* Gets all of the commands located in a configuration file.
*
* @return the commands parsed from the configuration file.
*/
public List<CommandInterface> getCommands()
{
try
{
autoUpdate();
}
catch (IOException e)
{
logger.error("Config file is no longer valid. For example, it might be deleted",e);
}
return exprEditors;
}
public CtClass getProxy(String className)
{
return customClasses.get(className);
}
}
| Java |
package org.annoflow.javassist;
import java.io.File;
import java.io.IOException;
import javassist.ClassPool;
import javassist.CtClass;
/**
* A factory for creating Translator objects. This stores configuration options
* for the creation of a configurable translator.
*/
public class TranslatorProvider
{
/** The eef singleton. */
private static TranslatorProvider eefSingleton = new TranslatorProvider();
/** The translator configs. */
private ConfigParser translatorConfig;
/**
* Instantiates a new translator factory.
*/
private TranslatorProvider()
{
}
/**
* Gets the expr editor factory.
*
* @return the expr editor factory
*/
public static TranslatorProvider getExprEditorFactory()
{
return eefSingleton;
}
/**
* Adds the config file.
*
* @param userFile
* the user file
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public void addConfigFile(File userFile,
ClassPool proxyPool) throws IOException
{
translatorConfig = new ConfigParser(userFile, proxyPool);
}
/**
* Gets a list of configurable translators from the configurations
* registered.
*
* @return the translators
*
* @throws MalformedConfigurationException
* the malformed configuration exception
*/
// public List<ConfigurableTranslatorLoader> getTranslators()
// throws MalformedConfigurationException
// {
// List<ConfigurableTranslatorLoader> translators = new ArrayList<ConfigurableTranslatorLoader>();
// try
// {
// translatorConfig.autoUpdate();
// }
// catch (IOException e)
// {
// translatorConfig = null;
// throw new MalformedConfigurationException("The configuration file has been removed from the system");
// }
// ConfigurableTranslatorLoader configTrans = new ConfigurableTranslatorLoader(translatorConfig);
// translators.add(configTrans);
//
// return translators;
// }
public CtClass getProxy(String className)
{
return translatorConfig.getProxy(className);
}
}
| Java |
package org.annoflow.javassist;
/**
* The Class MacroCall. This class represents a macro call located in the
* replacement text in a command. See macro class for more information
*/
public class MacroCall extends Macro
{
/**
* Instantiates a new macro call.
*
* @param userMacro
* the user macro call
*
* @throws MalformedMacroBodyException
* the malformed macro body exception
* @throws MalformedMacroNameException
* the malformed macro name exception
* @throws MalformedMacroParametersException
* the malformed macro parameters exception
*/
public MacroCall(String userMacro) throws MalformedMacroException
{
super(userMacro, "^%[a-zA-Z0-9]+\\(", "\\([^\\)]*\\)");
}
/*
* (non-Javadoc)
*
* @see cloudspace.vm.javassist.parsers.Macro#getMacroName()
*/
public String getMacroName()
{
String superName = super.getMacroName();
return superName.substring(1);
}
}
| Java |
package org.annoflow.javassist;
import java.util.List;
import javassist.CannotCompileException;
import javassist.CtClass;
/**
* The Class AbstractCommand. This class represents the most basic functions of
* a command as interpreted by a javassist configuration file.
*/
public abstract class AbstractCommand implements CommandInterface
{
/**
* The Class CommandNotImplementedException. This exception results from a
* command that requires operations not implemented by javassist.
*/
public class CommandNotImplementedException extends MalformedCommandException
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Instantiates a new command not implemented exception.
*
* @param command
* the command
*/
public CommandNotImplementedException(CommandInterface command)
{
super(
"The combination of Translation Type and Signature Type is not supported: "
+ command.toString());
}
}
/**
* The Class MalformedCommandArgumentException. This exception results from a
* command argument that is not properly formated in a javassist config file.
*/
public class MalformedCommandArgumentException extends
MalformedCommandException
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Instantiates a new malformed command argument exception.
*
* @param argList
* the arg list
*/
public MalformedCommandArgumentException(List<String> argList)
{
super("The arguments parsed are not in the correct format: "
+ argList.toString());
}
}
/**
* The Enum SignatureType. The type of signature to translate.
*/
public enum SignatureType
{
CONSTRUCTORCALL,
NEWEXPR,
METHODCALL,
STATICDEFINITION,
NEWARRAY,
FIELDACCESS,
INSTANCEOF,
CAST,
HANDLER,
METHODBODY
};
/** The sig type. */
SignatureType sigType;
/** The un parsed args. */
List<String> unParsedArgs;
/** The trans type. */
//TranslationType transType;
/** The command. */
String command;
/** The signature. */
String signature;
/**
* Instantiates a new abstract command using a list of arguments parsed from
* a configuration file.
*
* @param argList
* the arguments parsed from a javassist config file
*
* @throws MalformedCommandException
* the malformed command exception
*/
protected AbstractCommand(List<String> argList)
throws MalformedCommandException
{
unParsedArgs = argList;
sigType = findSignatureType();
//transType = findTranslationType();
signature = findSignature();
command = findReplacement();
}
/*
* (non-Javadoc)
*
* @see
* cloudspace.vm.javassist.commands.CommandInterface#getSignatureType
* ()
*/
public SignatureType getSignatureType()
{
return sigType;
}
public String getReplacement()
{
return command;
}
/*
* (non-Javadoc)
*
* @see
* cloudspace.vm.javassist.commands.CommandInterface#getSignature
* ()
*/
public String getSignature()
{
return signature;
}
public String getShortSignature()
{
int firstParen = signature.indexOf('(');
int lastPackageSep = signature.substring(0, firstParen).lastIndexOf('.');
return signature.substring(lastPackageSep+1);
}
// List<String> unParsedArgs;
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString()
{
return unParsedArgs.toString();
}
/**
* a utility method for finding replacement text
*
* @return the replacement text
*
* @throws MalformedCommandArgumentException
* the malformed command argument exception
*/
private String findReplacement() throws MalformedCommandArgumentException
{
String rep;
try
{
String replText = unParsedArgs.get(3).trim();
rep = replText.substring(1, unParsedArgs.get(3).length() - 1);
}
catch (IndexOutOfBoundsException ex)
{
throw new MalformedCommandArgumentException(unParsedArgs);
}
//rep =
rep = rep.trim();
return rep;
}
/*public String getDynamicReplacement()
{
//return "if($0 != null && !cloudspace.vm.javassist.ClassAnalyzer.rewriteNeeded($0.getClass(),\""+ getShortSignature() + "\")){ $_=$proceed($$);}else{" + getReplacement()+ "}";
return command;
}*/
/**
* A utility method for finding the signature.
*
* @return the string
*
* @throws MalformedCommandArgumentException
* the malformed command argument exception
*/
private String findSignature() throws MalformedCommandArgumentException
{
String sig;
try
{
sig = unParsedArgs.get(2);
}
catch (IndexOutOfBoundsException ex)
{
throw new MalformedCommandArgumentException(unParsedArgs);
}
return sig;
}
/**
* a utility method for finding the type of signature.
*
* @return the signature type
*
* @throws MalformedCommandArgumentException
* the malformed command argument exception
* @throws MalformedSignatureTypeException
* the malformed signature type exception
*/
private SignatureType findSignatureType()
throws MalformedCommandException
{
String commandType;
try
{
commandType = unParsedArgs.get(1);
}
catch (IndexOutOfBoundsException ex)
{
throw new MalformedCommandArgumentException(unParsedArgs);
}
if (commandType.equals("ConstructorCall"))
{
return SignatureType.CONSTRUCTORCALL;
}
else if (commandType.equals("NewExpr"))
{
return SignatureType.NEWEXPR;
}
else if (commandType.equals("MethodCall"))
{
return SignatureType.METHODCALL;
}
else if (commandType.equals("StaticDefinition"))
{
return SignatureType.STATICDEFINITION;
}
else if (commandType.equals("Handler"))
{
return SignatureType.HANDLER;
}
else if (commandType.equals("Cast"))
{
return SignatureType.CAST;
}
else if (commandType.equals("InstanceOf"))
{
return SignatureType.INSTANCEOF;
}
else if (commandType.equals("FieldAccess"))
{
return SignatureType.FIELDACCESS;
}
else if (commandType.equals("NewArray"))
{
return SignatureType.NEWARRAY;
}
else if (commandType.equals("MethodBody"))
{
return SignatureType.METHODBODY;
}
throw new MalformedCommandException("The signature type " + commandType + " is unknown in command: "
+ unParsedArgs.toString());
}
@Override
public void translate(CtClass clazz) throws MalformedCommandException, CannotCompileException
{
throw new CommandNotImplementedException(this);
}
}
| Java |
package org.annoflow.javassist;
import java.util.List;
import javassist.CannotCompileException;
import javassist.CtMethod;
import javassist.expr.Expr;
/**
* The Class Replace. This is the most simple and most widely supported command.
* this class allows for special handling of certain types of methods and
* expressions that may not be supported by javassist translations.
*
* translate Replace <Expression Type> <Method signature> <Replacement body>
*
*/
public class Replace extends AbstractCommand
{
/**
* Instantiates a new replace command.
*
* @param args
* the args
*
* @throws MalformedCommandException
* the malformed command exception
*/
public Replace(List<String> args) throws MalformedCommandException
{
super(args);
}
/*
* (non-Javadoc)
*
* @see cloudspace.vm.javassist.commands.CommandInterface#translate
* (javassist.expr.Expr, java.lang.String)
*/
public void translate(Expr call, boolean isSuper)
throws MalformedCommandException, CannotCompileException
{
//String signature = getSignature();
try
{
String repl = getReplacement();
call.replace(repl);
}
catch (CannotCompileException e)
{
throw new MalformedCommandException(e.getMessage() + ": "
+ getReplacement());
}
catch (RuntimeException e)
{
throw new CommandNotImplementedException(this);
}
}
/*
* (non-Javadoc)
*
* @see cloudspace.vm.javassist.commands.CommandInterface#translate
* (javassist.CtMethod, java.lang.String)
*/
@Override
public void translate(CtMethod member, String expressionName)
throws MalformedCommandException, CannotCompileException
{
throw new CommandNotImplementedException(this);
}
}
| Java |
package org.annoflow.javassist;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The Class MacroDefinition. this class represents a macro definition inside of
* a javassist configuration file. See Macro class for more information.
*/
public class MacroDefinition extends Macro
{
/** The command body. */
String commandBody;
/**
* Instantiates a new macro definition.
*
* @param userMacro
* the user macro
*
* @throws MalformedMacroBodyException
* the malformed macro body exception
* @throws MalformedMacroNameException
* the malformed macro name exception
* @throws MalformedMacroParametersException
* the malformed macro parameters exception
*/
public MacroDefinition(String userMacro)
throws MalformedMacroException
{
super(userMacro, "^[a-zA-Z0-9]+\\(", "\\([^\\)]*\\)");
commandBody = getCommmandBody(macro);
}
/**
* This method takes a user macro call and tailors the macro definition.
*
* @param mCall
* a macro call to define the macro definition.
*
* @return the tailored command
*
* @throws MacroCallMismatchException
* the macro call mismatch exception
*/
public String getTailoredCommand(MacroCall mCall)
throws MalformedMacroException
{
String tailoredBody = commandBody;
if (macroParams.size() != mCall.getNumberOfParams())
{
throw new MalformedMacroException("Macro call to "+mCall.getMacroName()+" has "+mCall.getNumberOfParams()+" and the definition has "+getNumberOfParams());
}
Iterator<String> defIter = macroParams.iterator();
Iterator<String> callIter = mCall.getParameterIterator();
while (defIter.hasNext() && callIter.hasNext())
{
String defParam = defIter.next();
String callParam = callIter.next();
tailoredBody = tailoredBody.replaceAll("%\\{\\s*" + defParam
+ "\\s*\\}", Matcher.quoteReplacement(callParam));
tailoredBody = tailoredBody.replaceAll("%" + defParam, Matcher
.quoteReplacement(callParam));
}
return tailoredBody;
}
private String getCommmandBody(String macro)
throws MalformedMacroException
{
Pattern commands = Pattern.compile("\\\".*\\\"");
Matcher commandMatcher = commands.matcher(macro);
String body = "";
if (commandMatcher.find())
{
body = commandMatcher.group();
}
else
{
throw new MalformedMacroException("Unable to find Macro Body in "+macro);
}
body = body.trim().substring(1, body.length() - 1);
return body;
}
}
| Java |
package org.annoflow.javassist;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.expr.Cast;
import javassist.expr.ConstructorCall;
import javassist.expr.Expr;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
import javassist.expr.Handler;
import javassist.expr.Instanceof;
import javassist.expr.MethodCall;
import javassist.expr.NewArray;
import javassist.expr.NewExpr;
import org.annoflow.javassist.AbstractCommand.SignatureType;
import org.apache.log4j.Logger;
/**
* The Class CustomExprEditor. This class is responsible for actually editing
* the
*/
public class CustomExprEditor extends ExprEditor
{
protected Logger logger = Logger.getLogger(CustomExprEditor.class);
private abstract class PrivlegedJavassistAction implements PrivilegedExceptionAction<String>
{
protected Object context;
public void setContext(Object context)
{
this.context = context;
}
}
Map<SignatureType, Map<String, List<CommandInterface>>> ExpressionNameToCommand;
/**
* Instantiates a new custom expr editor. from a list of commands. These
* commands are stored in seperate lists to be executed on method calls and
* expressions being translated.
*
* @param editConfigs
* commands to drive the configuration.
*/
public CustomExprEditor(List<CommandInterface> editConfigs)
{
ExpressionNameToCommand = new HashMap<SignatureType, Map<String, List<CommandInterface>>>();
for (CommandInterface curCommand : editConfigs)
{
// CommandInterface curCommand = commandIter.next();
Map<String, List<CommandInterface>> sigMap = ExpressionNameToCommand
.get(curCommand.getSignatureType());
if (sigMap == null)
{
sigMap = new HashMap<String, List<CommandInterface>>();
ExpressionNameToCommand.put(curCommand.getSignatureType(),
sigMap);
}
List<CommandInterface> commands = sigMap.get(curCommand
.getSignature());
if (commands == null)
{
commands = new LinkedList<CommandInterface>();
sigMap.put(curCommand.getSignature(), commands);
}
commands.add(curCommand);
}
}
/**
* this method is for static edits to a class. These happen once and are not
* iterated.
*
* @param clazz
* the clazz to be edited
*/
public synchronized void staticEdits(CtClass clazz)
{
Map<String, List<CommandInterface>> sigTypeMap = ExpressionNameToCommand
.get(SignatureType.METHODBODY);
performStaticEdits(clazz, sigTypeMap);
sigTypeMap = ExpressionNameToCommand
.get(SignatureType.STATICDEFINITION);
performStaticEdits(clazz, sigTypeMap);
}
private void performStaticEdits(CtClass clazz,
Map<String, List<CommandInterface>> sigTypeMap)
{
if (sigTypeMap != null)
{
for (CtMethod method : clazz.getDeclaredMethods())
{
String methodName = method.getLongName();
int nameStart = method.getLongName().substring(0,method.getLongName().indexOf('(')).lastIndexOf('.');
methodName = methodName.substring(nameStart+1);
List<CommandInterface> listOfCommands = sigTypeMap.get(methodName);
if (listOfCommands != null)
{
for (CommandInterface curCommand : listOfCommands)
{
// CommandInterface curCommand = iterCommand.next();
try
{
curCommand.translate(method,methodName);
}
catch (Exception e)
{
logger
.error("Could not perform Static edit: ["+methodName+","+curCommand.getSignature()+"]",e);
}
}
}
}
}
}
/**
* Conversion of an Expr.
*
* @param ccall
* the expression ccall
* @param commandList
* the list of commands to use to perform the edit.
* @param expressionName
* the name of the expression being edited.
*/
private void convert(Expr ccall, List<CommandInterface> commandList,
boolean isSuper)
{
if (commandList != null)
{
for (CommandInterface curCommand : commandList)
{
try
{
curCommand.translate(ccall, isSuper);
}
catch (MalformedCommandException e)
{
logger.error("The command is not written correctly please revise it: "+curCommand.toString(),e);
}
catch (CannotCompileException e)
{
logger.error("Could not compile the replacement text: "+curCommand.getReplacement(),e);
}
}
}
}
public List<CommandInterface> getCommandList(SignatureType sigType,
String signature)
{
Map<String, List<CommandInterface>> callToCommand = ExpressionNameToCommand
.get(sigType);
if (callToCommand != null)
{
return callToCommand.get(signature);
}
return null;
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.Handler)
*/
public void edit(Handler ccall)
{
/*try
{
PrivlegedJavassistAction action = new PrivlegedJavassistAction()
{
@Override
public String run() throws NotFoundException
{
CtClass type = ((Handler)context).getType();
if(type ==null)
{
return "";
}
return type.getName();
}
};
action.setContext(ccall);
String constName = AccessController.doPrivileged(action);
logger.trace("Attempting to rewrite "+constName);
//String handlerSig = ccall.getType().getName();
convert(ccall, getCommandList(SignatureType.HANDLER, constName),
false);
}
catch (PrivilegedActionException e)
{
logger.error("Exception occured rewriting a Handler call in "+ccall.getFileName());
e.printStackTrace();
}*/
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.Cast)
*/
public void edit(Cast ccall)
{
/*try
{
PrivlegedJavassistAction action = new PrivlegedJavassistAction()
{
@Override
public String run() throws NotFoundException
{
return ((Cast)context).getType().getName();
}
};
action.setContext(ccall);
String constName = AccessController.doPrivileged(action);
logger.trace("Attempting to rewrite "+constName);
convert(ccall, getCommandList(SignatureType.CAST, constName), false);
}
catch (PrivilegedActionException e)
{
logger.error("Exception occured rewriting a Cast call in "+ccall.getFileName());
e.printStackTrace();
}*/
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.Instanceof)
*/
public void edit(Instanceof ccall)
{
/*try
{
PrivlegedJavassistAction action = new PrivlegedJavassistAction()
{
@Override
public String run() throws NotFoundException
{
return ((Instanceof)context).getType().getName();
}
};
action.setContext(ccall);
String constName = AccessController.doPrivileged(action);
logger.trace("Attempting to rewrite "+constName);
convert(ccall, getCommandList(SignatureType.INSTANCEOF,
constName), false);
}
catch (PrivilegedActionException e)
{
logger.error("Exception occured rewriting a Instance of call in "+ccall.getFileName());
e.printStackTrace();
}*/
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.FieldAccess)
*/
public void edit(FieldAccess ccall)
{
// TODO: This probably does not work! If you attempt to access the field
// in a super class this may fall apart.
/* try
{
action.setClass(ccall.getType());
String fieldName = ccall.getField().getName();
convert(ccall,
getCommandList(SignatureType.FIELDACCESS, fieldName), false);
}
catch (NotFoundException e)
{
System.err.println("Could not find class for array type");
e.printStackTrace();
}*/
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.NewArray)
*/
public void edit(NewArray ccall)
{
/*try
{
PrivlegedJavassistAction action = new PrivlegedJavassistAction()
{
@Override
public String run() throws NotFoundException
{
return ((NewArray)context).getComponentType().getName();
}
};
action.setContext(ccall);
String constName = AccessController.doPrivileged(action);
logger.trace("Attempting to rewrite "+constName);
convert(ccall,
getCommandList(SignatureType.NEWARRAY, constName), false);
}
catch (PrivilegedActionException e)
{
logger.error("Exception occured rewriting a NewArray call in "+ccall.getFileName());
e.printStackTrace();
}*/
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.MethodCall)
*/
public void edit(MethodCall ccall)
{
try
{
PrivlegedJavassistAction action = new PrivlegedJavassistAction()
{
@Override
public String run() throws NotFoundException
{
return ((MethodCall)context).getMethod().getLongName();
}
};
action.setContext(ccall);
String constName = (String) AccessController.doPrivileged(action);
logger.trace("Attempting to rewrite "+constName);
convert(ccall, getCommandList(SignatureType.METHODCALL, constName),
ccall.isSuper());
}
catch (PrivilegedActionException e)
{
logger.error("Exception occured rewriting a MethodCall call in "+ccall.getFileName(),e);
}
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.ConstructorCall)
*/
public void edit(ConstructorCall ccall)
{
try
{
PrivlegedJavassistAction action = new PrivlegedJavassistAction()
{
@Override
public String run() throws NotFoundException
{
return ((ConstructorCall)context).getConstructor().getLongName();
}
};
action.setContext(ccall);
String constName = AccessController.doPrivileged(action);
logger.trace("Attempting to rewrite "+constName);
convert(ccall, getCommandList(SignatureType.CONSTRUCTORCALL,
constName), ccall.isSuper());
}
catch (PrivilegedActionException e)
{
logger.error("Exception occured rewriting a ConstructorCall call in "+ccall.getFileName(),e);
}
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.NewExpr)
*/
public void edit(NewExpr ccall)
{
try
{
PrivlegedJavassistAction action = new PrivlegedJavassistAction()
{
@Override
public String run() throws NotFoundException
{
return ((NewExpr)context).getConstructor().getLongName();
}
};
action.setContext(ccall);
String constName = AccessController.doPrivileged(action);
logger.trace("Attempting to rewrite "+constName);
convert(ccall, getCommandList(SignatureType.NEWEXPR, constName), false);
}
catch (PrivilegedActionException e)
{
logger.error("Exception occured rewriting a NewExpr call in "+ccall.getFileName(),e);
}
}
}
| Java |
package org.annoflow.javassist;
public class MalformedMacroException extends MalformedConfigurationException
{
/**
*
*/
private static final long serialVersionUID = 1L;
public MalformedMacroException(String message)
{
super(message);
}
}
| Java |
package org.annoflow.javassist.test;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import org.annoflow.javassist.AnnoTranslator;
import org.annoflow.javassist.ConfigParser;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.Loader;
import javassist.NotFoundException;
import junit.framework.TestCase;
public class JavassistTestCase extends TestCase
{
ClassPool pool;
ClassLoader loader;
AnnoTranslator translator;
public void setUp()
{
try
{
pool = new ClassPool();
pool.appendClassPath("bin");
pool.appendSystemPath();
translator= new AnnoTranslator(new ConfigParser(new File("default.conf"),pool));
loader = this.getClass().getClassLoader();
// loader = new Loader(pool);
// try
// {
// ((Loader)loader).addTranslator(pool, translator);
// }
// catch (CannotCompileException e)
// {
// e.printStackTrace();
// }
}
catch (NotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public Object runMethod(String classToLoad, String methodToTest, Class<?>[] methodToTestArgs,
Object argsToTest) throws Exception
{
Class<?> rewrittenClass = loadClass(classToLoad);
Method methodToRun = getClassMethod(rewrittenClass, methodToTest, methodToTestArgs);
Object objectReturned = invokeMethod(methodToRun, argsToTest);
return objectReturned;
}
private Object invokeMethod(Method methodToRun, Object args)
throws Exception
{
Object createdObject = null;
createdObject = (Object) methodToRun.invoke(null, (Object[]) args);
return createdObject;
}
private Method getClassMethod(Class<?> rewrittenClass, String methodName, Class<?>[] args) throws Exception
{
Method methodToRun = null;
// Strange.....
if (args == null)
{
methodToRun = rewrittenClass.getDeclaredMethod(methodName, (Class[]) null);
}
else
{
methodToRun = rewrittenClass.getDeclaredMethod(methodName, args);
}
return methodToRun;
}
protected Class<?> loadClass(String classToLoad) throws Exception
{
return loader.loadClass(classToLoad);
}
}
| Java |
package org.annoflow.audit;
import java.util.Date;
import org.annoflow.audit.Logger.LogLevel;
import org.annoflow.policy.PolicyType;
public class Data {
// private String from;
private Class<?> to;
private String auditText;
private LogLevel level;
private PolicyType policySnapshot;
private long timestamp;
public Data(LogLevel level, Class<?> to, PolicyType policy,
String auditText) {
this.level = level;
// this.from = from;
this.to = to;
this.policySnapshot = policy;
this.auditText = auditText;
this.timestamp = System.currentTimeMillis();
}
// public String getFrom() {
// return from;
// }
public String getTo() {
return to.getName();
}
public String getAuditText() {
return auditText;
}
public LogLevel getLogLevel() {
return level;
}
public String getLevel() {
switch (level) {
case OUT:
return "Normal";
case ERROR:
return "Error";
}
return "";
}
public PolicyType getPolicySnapshot() {
return policySnapshot;
}
public String getObjectPolicy()
{
if(policySnapshot != null)
{
return policySnapshot.getClass().getName();
}
return "";
}
public Date getTime()
{
return new Date(timestamp);
}
} | Java |
package org.annoflow.audit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.annoflow.policy.PolicyManager;
import org.annoflow.policy.PolicyType;
public abstract class Logger {
public enum LogLevel {
ERROR, OUT
}
private static Map<String,List<Data>> filterToData = new HashMap<String,List<Data>>();
/**
* Report an error audit to annoflow
* @param elements a stack trace at the {@link PolicyType#audit()} call.
* @param object the object being audited
* @param auditText the text created by the audit.
*/
public synchronized static void error(String filterName, Class<?> classOwner, Object object, String auditText)
{
addToLog(LogLevel.ERROR,filterName,classOwner, object, auditText);
}
/**
* Report an event (Non-error) audit to annoflow
* @param elements a stack trace at the {@link PolicyType#audit()} call.
* @param object the object being audited
* @param auditText the text created by the audit.
*/
public synchronized static void out(String filterName, Class<?> classOwner, Object object, String auditText)
{
addToLog(LogLevel.OUT,filterName,classOwner, object, auditText);
}
private static void addToLog(LogLevel level, String filterName, Class<?> classOwner, Object object, String auditText) {
PolicyType objectPolicy = PolicyManager.lookupObjectPolicy(object);
Data toLog = new Data(level,classOwner,objectPolicy,auditText);
List<Data> filterData = filterToData.get(filterName);
if(filterData == null)
{
filterData = new LinkedList<Data>();
filterToData.put(filterName, filterData);
}
filterData.add(toLog);
}
public synchronized static Set<String> getFilterPoints()
{
return filterToData.keySet();
}
public synchronized static List<Data> getFilterData(String filterPoint)
{
return filterToData.get(filterPoint);
}
}
| Java |
package org.annoflow.audit;
public class ContextTracker {
private static ContextTracker tracker = new ContextTracker();
// private ThreadLocal<String> callerContext = new ThreadLocal<String>();
private ThreadLocal<Class<?>> filterContext = new ThreadLocal<Class<?>>();
private ThreadLocal<String> callerContext = new ThreadLocal<String>();
private ContextTracker()
{
callerContext.set(null);
filterContext.set(null);
}
public static ContextTracker getInstance()
{
return tracker;
}
public void setFilterContext(Class<?> caller)
{
filterContext.set(caller);
}
public Class<?> getFilterContext()
{
return filterContext.get();
}
public String getCallerContext()
{
return callerContext.get();
}
public void setCallerContext(String caller)
{
callerContext.set(caller);
}
public void clear()
{
filterContext.set(null);
callerContext.set(null);
}
}
| Java |
package org.annoflow.policy;
import java.util.HashMap;
import java.util.LinkedList;
import org.annoflow.policy.boundry.InsecureClassPolicy;
import org.annoflow.util.WeakIdentityHashMap;
public class PolicyManager
{
private static HashMap<String, PolicyType> classPolicies = null;
private static WeakIdentityHashMap<Object, PolicyType> objectPolicies = null;
private static HashMap<Object, LinkedList<Object>> parentMap = null;
public static void addClassPolicy(Class<?> clazz, PolicyType policy)
{
//System.err.println("Adding class Policy: " + clazz.getName() + " " + policy.getClass().getName());
if (classPolicies == null)
{
classPolicies = new HashMap<String, PolicyType>();
}
classPolicies.put(clazz.getName(), policy);
}
public static void addFieldPolicy(Object o, Object parent, Class<? extends PolicyType> policyClass)
{
if (objectPolicies == null)
{
objectPolicies = new WeakIdentityHashMap<Object, PolicyType>();
}
if (parentMap == null)
{
parentMap = new HashMap<Object, LinkedList<Object>>();
}
PolicyType policy = null;
try {
policy = policyClass.newInstance();
} catch (InstantiationException e) {
return;
} catch (IllegalAccessException e) {
return;
}
if(o != null)
{
objectPolicies.put(o, policy);
}
if (parent != null)
{
if (parentMap.containsKey(parent))
{
parentMap.get(parent).add(o);
}
else
{
LinkedList<Object> list = new LinkedList<Object>();
list.add(o);
parentMap.put(parent, list);
}
}
}
public static void addObjectPolicy(Object o)
{
//System.err.println("Adding object policy " + o.getClass());
PolicyType classPolicy;
if(o != null)
{
classPolicy = lookupClassPolicy(o.getClass());
}
else
{
classPolicy = null;
}
if (classPolicy != null)
{
classPolicy = classPolicy.generateOrigin();
//AbstractPolicy objectPolicy = classPolicy.generatePolicy(o);
if (objectPolicies == null)
{
objectPolicies = new WeakIdentityHashMap<Object, PolicyType>();
}
objectPolicies.put(o, classPolicy);
}
}
public static PolicyType lookupClassPolicy(Class<?> clazz)
{
//System.err.println("1Looking up " + clazz.getName());
//new Exception().printStackTrace();
if (classPolicies == null)
{
classPolicies = new HashMap<String, PolicyType>();
}
return classPolicies.get(clazz.getName());
}
public static PolicyType lookupObjectPolicy(Object o)
{
if(o == null)
return null;
if (objectPolicies == null)
{
objectPolicies = new WeakIdentityHashMap<Object, PolicyType>();
}
PolicyType objectPolicy = objectPolicies.get(o);
if (objectPolicy != null)
{
return objectPolicy;
}
objectPolicy = lookupClassPolicy(o.getClass());
return objectPolicy;
}
public static void setObjectPolicy(Object self,
PolicyType classPolicy) {
if (objectPolicies == null)
{
objectPolicies = new WeakIdentityHashMap<Object, PolicyType>();
}
objectPolicies.put(self, classPolicy);
}
public static HashMap<Object, PolicyType> lookupParentPolicy(Object parent) {
if (parentMap == null) {
parentMap = new HashMap<Object, LinkedList<Object>>();
}
HashMap<Object, PolicyType> ans = new HashMap<Object, PolicyType>();
if (parentMap.containsKey(parent)) {
for (Object obj : parentMap.get(parent)) {
ans.put(obj, lookupObjectPolicy(obj));
}
}
return ans;
}
}
| Java |
package org.annoflow.policy;
import java.util.HashMap;
import org.annoflow.policy.boundry.SecureClassPolicy;
public class UserInputPolicy implements PolicyType {
private static final String assessCheck = "target";
@Override
public void assess(HashMap<String, String> context) throws Exception {
if ("html".equals(context.get(assessCheck))) {
throw new Exception();
}
if ("sql".equals(context.get(assessCheck))) {
throw new Exception();
}
}
@Override
public boolean audit(Object o, String filterName, Class<?> methodOwner) {
// TODO Auto-generated method stub
return false;
}
@Override
public PolicyType generateOrigin() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getPolicyCode() {
return "org.annoflow.policy.UserInputPolicy.addPolicy($class);";
}
public static void addPolicy(Class<?> clazz)
{
PolicyManager.addClassPolicy(clazz, new UserInputPolicy());
}
}
| Java |
package org.annoflow.policy;
import java.util.HashMap;
public class TopSecretPolicy implements PolicyType
{
public TopSecretPolicy() {}
@Override
public void assess(HashMap<String, String> context) throws Exception {
if ("topsecret".equals(context.get("level")))
return;
throw new Exception();
}
@Override
public boolean audit(Object o,String filterName,Class<?> methodOwner) {
return true;
}
public String getPolicyCode()
{
return "org.annoflow.policy.TopSecretPolicy.addPolicy($class);";
}
@Override
public PolicyType generateOrigin() {
// TODO Auto-generated method stub
return null;
}
public static void addPolicy(Class<?> clazz) {
PolicyManager.addClassPolicy(clazz, new TopSecretPolicy());
}
}
| Java |
package org.annoflow.policy;
public @interface TopSecret {
}
| Java |
package org.annoflow.policy;
import java.util.HashMap;
public interface PolicyType {
public void assess(HashMap<String, String> context) throws Exception;
public boolean audit(Object o,String filterName, Class<?> methodOwner);
public String getPolicyCode();
public PolicyType generateOrigin();
}
| Java |
package org.annoflow.policy;
import java.util.HashMap;
public class AnchoredPolicy implements PolicyType {
@Override
public void assess(HashMap<String, String> context) throws Exception {
if ("network".equals(context.get("type")))
throw new Exception();
}
@Override
public boolean audit(Object o,String filterName, Class<?> methodOwner) {
return false;
}
@Override
public String getPolicyCode() {
return "org.annoflow.policy.AnchoredPolicy.addPolicy($class);";
}
@Override
public PolicyType generateOrigin() {
// TODO Auto-generated method stub
return null;
}
public static void addPolicy(Class<?> clazz) {
PolicyManager.addClassPolicy(clazz, new AnchoredPolicy());
}
}
| Java |
package org.annoflow.policy.boundry;
import java.util.HashMap;
import org.annoflow.audit.ContextTracker;
import org.annoflow.audit.Logger;
import org.annoflow.policy.PolicyType;
import org.annoflow.policy.PolicyManager;
public class SecureClassPolicy implements PolicyType {
@Override
public void assess(HashMap<String, String> context) throws Exception {
}
@Override
public boolean audit(Object o,String filterName, Class<?> methodOwner) {
String caller = ContextTracker.getInstance().getCallerContext();
// StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
// StackTraceElement element = stackTrace[stackTrace.length - 1];
try {
Class<?> parentCaller = Class.forName(caller);
PolicyType policy = PolicyManager.lookupClassPolicy(parentCaller);
if (policy == null || !policy.equals(SecureClassPolicy.class)) {
// StackTraceElement[] elements = Thread.currentThread().getStackTrace();
Logger.out(filterName,methodOwner,o,"This class is being passed into an insecure class");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
@Override
public String getPolicyCode() {
return "org.annoflow.policy.boundry.SecureClassPolicy.addPolicy($class);";
}
public static void addPolicy(Class<?> clazz)
{
PolicyManager.addClassPolicy(clazz, new SecureClassPolicy());
}
@Override
public PolicyType generateOrigin() {
if(isCallerSecure())
{
return new SecureClassPolicy();
}
return new InsecureClassPolicy();
}
private boolean isCallerSecure()
{
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement element = stackTrace[4];
// String caller = ContextTracker.getInstance().getCallerContext();
String caller = element.getClassName();
try {
Class<?> parentCaller = Thread.currentThread().getContextClassLoader().loadClass(caller);
PolicyType policy = PolicyManager.lookupClassPolicy(parentCaller);
if (policy == null || !(policy instanceof SecureClassPolicy)) {
return false;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return true;
}
}
| Java |
package org.annoflow.policy;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
public @interface Policy {
Class<? extends PolicyType> policy();
}
| Java |
package org.annoflow.filter.perf;
import org.annoflow.audit.ContextTracker;
import org.annoflow.audit.Logger;
import org.annoflow.filter.FilterPoint;
public class TimerFilter implements FilterPoint {
private static long timer = 0L;
@Override
public String getFilterCode() {
return "org.annoflow.filter.perf.TimerFilter.startTimer($args);";
}
@Override
public String getReturnFilterCode() {
return "org.annoflow.filter.perf.TimerFilter.stopTimer($_);";
}
public static void startTimer(Object[] args) {
timer = System.currentTimeMillis();
}
public static void stopTimer(Object value) {
long diff = System.currentTimeMillis() - timer;
// Logger.out(TimerFilter.class.getName(),
// ContextTracker.getInstance().getFilterContext(),
// null,
// "Took " + diff + " ms.");
System.out.println(diff);
}
}
| Java |
package org.annoflow.filter.xss;
import java.util.HashMap;
import org.annoflow.filter.FilterPoint;
import org.annoflow.policy.PolicyManager;
import org.annoflow.policy.PolicyType;
public class XSSFilter implements FilterPoint {
@Override
public String getFilterCode() {
return "org.annoflow.filter.xss.XSSFilter.runFilter($args);";
}
public static void runFilter(Object[] args) throws Exception {
for (Object arg : args) {
//First check if it's a string
if (arg instanceof String) {
if (isInvalidHTML((String)arg)) {
throw new Exception();
}
}
//Next check if there's a policy on the object being passed in
PolicyType policy = null;
if ((policy = PolicyManager.lookupObjectPolicy(arg)) != null) {
HashMap<String,String> context = new HashMap<String, String>();
context.put("target", "html");
policy.assess(context);
}
//Finally check if there's a policy on any of the object's fields
HashMap<Object,PolicyType> fields = null;
if((fields = PolicyManager.lookupParentPolicy(arg)) != null) {
HashMap<String,String> context = new HashMap<String, String>();
context.put("target", "html");
for (Object field : fields.keySet()) {
fields.get(field).assess(context);
}
}
}
}
private static boolean isInvalidHTML(String arg) {
return arg.contains("<script>") || arg.contains("</script>");
}
@Override
public String getReturnFilterCode() {
return null;
}
}
| Java |
package org.annoflow.filter;
public class FilterParser
{
}
| Java |
package org.annoflow.filter;
import java.util.HashMap;
import org.annoflow.policy.PolicyType;
import org.annoflow.policy.PolicyManager;
import org.apache.log4j.Logger;
public class NetworkFilter implements FilterPoint
{
private static Logger logger = Logger.getLogger(AuditFilter.class);
@Override
public String getFilterCode()
{
return "org.annoflow.filter.NetworkFilter.runFilter($args);";
}
public static void runFilter(Object[] args)
{
logger.info("Executing NetworkFilter");
//Setup context parameters
HashMap<String, String> params = new HashMap<String, String>();
params.put("type", "network");
//Check arguments to method
PolicyType policy = null;
for(Object arg : args) {
policy = null;
if ((policy = PolicyManager.lookupClassPolicy(arg.getClass())) != null) {
try {
policy.assess(params);
}
catch (Exception ex) {
throw new RuntimeException();
}
}
}
}
@Override
public String getReturnFilterCode() {
// TODO Auto-generated method stub
return null;
}
}
| Java |
package org.annoflow.filter.auth;
import org.annoflow.audit.Logger;
import org.annoflow.filter.FilterPoint;
public class LoginStatusFilter implements FilterPoint {
@Override
public String getFilterCode() {
return null;
//return "org.annoflow.filter.auth.LoginStatusFilter.logFail($0,$$);";
}
public static void logFail(Object o,String message)
{
Logger.error(LoginStatusFilter.class.getName(), o.getClass(), o, message);
}
@Override
public String getReturnFilterCode() {
return "$_ = ($r)org.annoflow.filter.auth.LoginStatusFilter.logFailure($0, $_);";
}
public static Object logFailure(Object owner, boolean val) {
// if (val instanceof Boolean) {
if (!((Boolean)val).booleanValue()) {
Logger.error(
LoginStatusFilter.class.getName(), owner.getClass(), owner, "Failed login");
}
// }
return val;
}
}
| Java |
package org.annoflow.filter.auth;
import org.annoflow.audit.ContextTracker;
import org.annoflow.audit.Logger;
import org.annoflow.filter.FilterPoint;
public class NewUserFilter implements FilterPoint {
@Override
public String getFilterCode() {
return "org.annoflow.filter.auth.NewUserFilter.logNewUser($$);";
}
public static void logNewUser(String userName,String password)
{
Logger.out(NewUserFilter.class.getName(), ContextTracker.getInstance().getFilterContext(), null, "Created new user: "+userName+":"+password);
}
@Override
public String getReturnFilterCode() {
// TODO Auto-generated method stub
return null;
}
}
| Java |
package org.annoflow.filter.locality;
import java.io.File;
import org.annoflow.filter.FilterPoint;
import org.annoflow.policy.Policy;
import org.annoflow.policy.PolicyType;
import org.annoflow.policy.locality.LocalizeClassPolicy;
public class LocalFileFilter implements FilterPoint{
@Override
public String getFilterCode() {
return "org.annoflow.filter.locality.enforceLocal($$);$_=$proceed($$);";
}
public static void enforceLocal(String path)
{
enforceLocal(new File(path));
}
public static void enforceLocal(File path)
{
if(path.getAbsolutePath().contains("remote"))
{
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for(StackTraceElement element : elements)
{
try {
Class<?> stackClass = Class.forName(element.getClassName());
Policy localPolicy = stackClass.getAnnotation(Policy.class);
if(localPolicy != null)
{
Class<? extends PolicyType> exactPolicy = localPolicy.policy();
if(exactPolicy.getCanonicalName().equals(LocalizeClassPolicy.class.getCanonicalName()))
{
throw new LocalizedException("There is a remote file being opened for writing or reading within the callpath");
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public String getReturnFilterCode() {
// TODO Auto-generated method stub
return null;
}
}
| Java |
package org.annoflow.filter.locality;
public class LocalizedException extends RuntimeException {
public LocalizedException(String message) {
super(message);
}
/**
*
*/
private static final long serialVersionUID = -5390232284018186386L;
}
| Java |
package org.annoflow.filter;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
public @interface Filter
{
Class<? extends FilterPoint> type();
}
| Java |
package org.annoflow.filter;
import org.annoflow.audit.ContextTracker;
import org.annoflow.policy.PolicyType;
import org.annoflow.policy.PolicyManager;
import org.apache.log4j.Logger;
public class AuditFilter implements FilterPoint
{
private static Logger logger = Logger.getLogger(AuditFilter.class);
@Override
public String getFilterCode()
{
return "org.annoflow.filter.AuditFilter.runFilter($args);";
}
public static void runFilter(Object[] args)
{
logger.info("AuditFilterExecuting");
PolicyType policy = null;
for(Object arg : args)
{
policy = null;
if ((policy = PolicyManager.lookupClassPolicy(arg.getClass())) != null)
{
if (policy.audit(arg,AuditFilter.class.getName(),ContextTracker.getInstance().getFilterContext()))
{
System.out.println("AUDIT: " + policy.getClass().getSimpleName() + " " + arg);
}
}
}
}
@Override
public String getReturnFilterCode() {
// TODO Auto-generated method stub
return null;
}
}
| Java |
package org.annoflow.filter.sqli;
import java.util.HashMap;
import org.annoflow.audit.ContextTracker;
import org.annoflow.audit.Logger;
import org.annoflow.filter.FilterPoint;
import org.annoflow.policy.PolicyManager;
import org.annoflow.policy.PolicyType;
public class SQLBoundFilter implements FilterPoint {
@Override
public String getFilterCode() {
return "org.annoflow.filter.sqli.SQLBoundFilter.runFilter($args);";
}
public static void runFilter(Object[] args) throws Exception {
for (Object arg : args) {
if (arg instanceof String) {
String potentialSQL = (String) arg;
if (containsSQL(potentialSQL)) {
// StackTraceElement[] elements = Thread.currentThread().getStackTrace();
Logger.error(SQLBoundFilter.class.getName(),ContextTracker.getInstance().getFilterContext(),arg,"Suspicious SQL: " + arg);
throw new Exception();
}
}
// //Next check if there's a policy on the object being passed in
// PolicyType policy = null;
// if ((policy = PolicyManager.lookupObjectPolicy(arg)) != null) {
// HashMap<String,String> context = new HashMap<String, String>();
// context.put("target", "sql");
// policy.assess(context);
// }
//
// //Finally check if there's a policy on any of the object's fields
// HashMap<Object,PolicyType> fields = null;
// if((fields = PolicyManager.lookupParentPolicy(arg)) != null) {
// HashMap<String,String> context = new HashMap<String, String>();
// context.put("target", "sql");
// for (Object field : fields.keySet()) {
// fields.get(field).assess(context);
// }
// }
}
}
private static boolean containsSQL(String potential) {
return potential.contains("WHERE") || potential.contains("SELECT")
|| potential.contains("DROP") || potential.contains("TRUNCATE");
}
@Override
public String getReturnFilterCode() {
// TODO Auto-generated method stub
return null;
}
}
| Java |
package org.annoflow.filter.boundry;
public class UnsecureCallException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = 1L;
public UnsecureCallException(String message)
{
super(message);
}
}
| Java |
package org.annoflow.filter.boundry;
import org.annoflow.audit.ContextTracker;
import org.annoflow.filter.FilterPoint;
import org.annoflow.policy.PolicyType;
import org.annoflow.policy.PolicyManager;
import org.annoflow.policy.boundry.InsecureClassPolicy;
import org.annoflow.policy.boundry.SecureClassPolicy;
public class SecureMethodFilter implements FilterPoint {
@Override
public String getFilterCode() {
return "org.annoflow.filter.boundry.SecureMethodFilter.checkCaller($0);";
}
public static void checkCaller(Object o)
{
try {
String context = ContextTracker.getInstance().getCallerContext();
Class<?> clazz;
PolicyType classPolicy, objectPolicy;
if(context != null)
{
clazz = o.getClass().forName(context, true, o.getClass().getClassLoader());
classPolicy = PolicyManager.lookupClassPolicy(clazz);
}
else
{
clazz = null;
classPolicy = null;
}
objectPolicy = PolicyManager.lookupObjectPolicy(o);
if(!(objectPolicy == null || objectPolicy instanceof InsecureClassPolicy) && (classPolicy == null ||classPolicy instanceof InsecureClassPolicy))
{
throw new UnsecureCallException("The method was called by an unsecure class.");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.err.println("Could not check Caller");
}
}
@Override
public String getReturnFilterCode() {
// TODO Auto-generated method stub
return null;
}
}
| Java |
package org.annoflow.filter.boundry;
import org.annoflow.audit.ContextTracker;
import org.annoflow.filter.FilterPoint;
import org.annoflow.policy.PolicyType;
import org.annoflow.policy.PolicyManager;
import org.annoflow.policy.boundry.InsecureClassPolicy;
import org.annoflow.policy.boundry.SecureClassPolicy;
public class MixFilter implements FilterPoint{
@Override
public String getFilterCode() {
return "org.annoflow.filter.boundry.MixFilter.mixParams(this);";
}
public static void mixParams(Object self)
{
PolicyType selfPolicy = PolicyManager.lookupObjectPolicy(self);
if(selfPolicy instanceof SecureClassPolicy)
{
if(!isCallerSecure())
{
PolicyManager.setObjectPolicy(self, new InsecureClassPolicy());
}
}
}
//TODO: Refactor
private static boolean isCallerSecure()
{
// StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
// StackTraceElement element = stackTrace[4];
String caller = ContextTracker.getInstance().getCallerContext();
try {
Class<?> parentCaller = Class.forName(caller);
PolicyType policy = PolicyManager.lookupClassPolicy(parentCaller);
if (policy != null) {
if (!policy.getClass().equals(SecureClassPolicy.class)) {
return false;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return true;
}
@Override
public String getReturnFilterCode() {
// TODO Auto-generated method stub
return null;
}
}
| Java |
package org.annoflow.filter;
public interface FilterPoint
{
public String getFilterCode();
public String getReturnFilterCode();
}
| Java |
/*
* @(#)WeakHashMap.java 1.30 04/02/19
*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package org.annoflow.util;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* This is a modified version of @see{WeakHashMap} from JDK 1.5.
* This modification uses System.identityHashCode() rather than
* the object's hash code. All equality checks are identity checks
* (==) rather than objet equality (.equals); @see{IdentityHashMap}
* for more information on the changes made in an identity hash map.
*
* A hashtable-based <tt>Map</tt> implementation with <em>weak
* keys</em>. An entry in a <tt>WeakIdentityHashMap</tt> will
* automatically be removed when its key is no longer in ordinary use.
* More precisely, the presence of a mapping for a given key will not
* prevent the key from being discarded by the garbage collector, that
* is, made finalizable, finalized, and then reclaimed. When a key
* has been discarded its entry is effectively removed from the map,
* so this class behaves somewhat differently than other <tt>Map</tt>
* implementations.
*
* <p> Both null values and the null key are supported. This class has
* performance characteristics similar to those of the <tt>HashMap</tt>
* class, and has the same efficiency parameters of <em>initial capacity</em>
* and <em>load factor</em>.
*
* <p> Like most collection classes, this class is not synchronized. A
* synchronized <tt>WeakIdentityHashMap</tt> may be constructed using the
* <tt>Collections.synchronizedMap</tt> method.
*
* <p> The behavior of the <tt>WeakIdentityHashMap</tt> class depends
* in part upon the actions of the garbage collector, so several
* familiar (though not required) <tt>Map</tt> invariants do not hold
* for this class. Because the garbage collector may discard keys at
* any time, a <tt>WeakIdentityHashMap</tt> may behave as though an
* unknown thread is silently removing entries. In particular, even
* if you synchronize on a <tt>WeakIdentityHashMap</tt> instance and
* invoke none of its mutator methods, it is possible for the
* <tt>size</tt> method to return smaller values over time, for the
* <tt>isEmpty</tt> method to return <tt>false</tt> and then
* <tt>true</tt>, for the <tt>containsKey</tt> method to return
* <tt>true</tt> and later <tt>false</tt> for a given key, for the
* <tt>get</tt> method to return a value for a given key but later
* return <tt>null</tt>, for the <tt>put</tt> method to return
* <tt>null</tt> and the <tt>remove</tt> method to return
* <tt>false</tt> for a key that previously appeared to be in the map,
* and for successive examinations of the key set, the value set, and
* the entry set to yield successively smaller numbers of elements.
*
* <p> Each key object in a <tt>WeakIdentityHashMap</tt> is stored
* indirectly as the referent of a weak reference. Therefore a key
* will automatically be removed only after the weak references to it,
* both inside and outside of the map, have been cleared by the
* garbage collector.
*
* <p> <strong>Implementation note:</strong> The value objects in a
* <tt>WeakIdentityHashMap</tt> are held by ordinary strong
* references. Thus care should be taken to ensure that value objects
* do not strongly refer to their own keys, either directly or
* indirectly, since that will prevent the keys from being discarded.
* Note that a value object may refer indirectly to its key via the
* <tt>WeakIdentityHashMap</tt> itself; that is, a value object may
* strongly refer to some other key object whose associated value
* object, in turn, strongly refers to the key of the first value
* object. One way to deal with this is to wrap values themselves
* within <tt>WeakReferences</tt> before inserting, as in:
* <tt>m.put(key, new WeakReference(value))</tt>, and then unwrapping
* upon each <tt>get</tt>.
*
* <p>The iterators returned by all of this class's "collection view methods"
* are <i>fail-fast</i>: if the map is structurally modified at any time after
* the iterator is created, in any way except through the iterator's own
* <tt>remove</tt> or <tt>add</tt> methods, the iterator will throw a
* <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the
* future.
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
* throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i>
*
* <p>This class is a member of the
* <a href="{@docRoot}/../guide/collections/index.html">
* Java Collections Framework</a>.
*
* @version 1.30, 02/19/04
* @author Doug Lea
* @author Josh Bloch
* @author Mark Reinhold
* @since 1.2
* @see java.util.HashMap
* @see java.lang.ref.WeakReference
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public class WeakIdentityHashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V> {
/**
* The default initial capacity -- MUST be a power of two.
*/
private static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
private static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load fast used when none specified in constructor.
*/
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
private /*@Nullable*/ Entry<K,V>[] table;
/**
* The number of key-value mappings contained in this weak hash map.
*/
private int size;
/**
* The next size value at which to resize (capacity * load factor).
*/
private int threshold;
/**
* The load factor for the hash table.
*/
private final float loadFactor;
/**
* Reference queue for cleared WeakEntries
*/
private final ReferenceQueue<K> queue = new ReferenceQueue<K>();
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
private volatile int modCount;
/**
* Constructs a new, empty <tt>WeakIdentityHashMap</tt> with the
* given initial capacity and the given load factor.
*
* @param initialCapacity The initial capacity of the
* <tt>WeakIdentityHashMap</tt>
* @param loadFactor The load factor of the
* <tt>WeakIdentityHashMap</tt>
* @throws IllegalArgumentException If the initial capacity is negative,
* or if the load factor is nonpositive.
*/
public WeakIdentityHashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Initial Capacity: "+
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load factor: "+
loadFactor);
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;
Entry<K,V>[] tmpTable = (Entry<K,V>[]) new Entry[capacity];
table = tmpTable;
this.loadFactor = loadFactor;
threshold = (int)(capacity * loadFactor);
}
/**
* Constructs a new, empty <tt>WeakIdentityHashMap</tt> with the
* given initial capacity and the default load factor, which is
* <tt>0.75</tt>.
*
* @param initialCapacity The initial capacity of the
* <tt>WeakIdentityHashMap</tt>
* @throws IllegalArgumentException If the initial capacity is negative.
*/
public WeakIdentityHashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs a new, empty <tt>WeakIdentityHashMap</tt> with the
* default initial capacity (16) and the default load factor
* (0.75).
*/
public WeakIdentityHashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
threshold = DEFAULT_INITIAL_CAPACITY;
Entry<K,V>[] tmpTable = (Entry<K,V>[]) new Entry[DEFAULT_INITIAL_CAPACITY];
table = tmpTable;
}
/**
* Constructs a new <tt>WeakIdentityHashMap</tt> with the same
* mappings as the specified <tt>Map</tt>. The
* <tt>WeakIdentityHashMap</tt> is created with default load
* factor, which is <tt>0.75</tt> and an initial capacity
* sufficient to hold the mappings in the specified <tt>Map</tt>.
*
* @param t the map whose mappings are to be placed in this map.
* @throws NullPointerException if the specified map is null.
* @since 1.3
*/
public WeakIdentityHashMap(Map<? extends K, ? extends V> t) {
this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1, 16),
DEFAULT_LOAD_FACTOR);
putAll(t);
}
// internal utilities
/**
* Value representing null keys inside tables.
*/
// This is problematic because it isn't of the right type.
// We can't lie here to the type system by claiming it is of type K,
// because NULL_KEY is a static field but K is a per-instance type parameter.
private static final Object NULL_KEY = new Object();
/**
* Use NULL_KEY for key if it is null.
*/
// not: "private static <K> K maskNull(K key)" because NULL_KEY isn't of type K.
private static /*@NonNull*/ Object maskNull(/*@Nullable*/ Object key) {
return (key == null ? NULL_KEY : key);
}
/**
* Return internal representation of null key back to caller as null
*/
private static <K> /*@Nullable*/ K unmaskNull(K key) {
return (key == NULL_KEY ? null : key);
}
/**
* Check for equality of non-null reference x and possibly-null y. Uses
* identity equality.
*/
static boolean eq(Object x, /*@Nullable*/ Object y) {
return x == y;
}
/** Return the hash code for x **/
static int hasher (Object x) {
return System.identityHashCode (x);
}
/**
* Return index for hash code h.
*/
static int indexFor(int h, int length) {
return h & (length-1);
}
/**
* Expunge stale entries from the table.
*/
private void expungeStaleEntries() {
Entry<K,V> e;
// These types look wrong to me.
while ( (e = (Entry<K,V>) queue.poll()) != null) { // unchecked cast
int h = e.hash;
int i = indexFor(h, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> p = prev;
while (p != null) {
Entry<K,V> next = p.next;
if (p == e) {
if (prev == e)
table[i] = next;
else
prev.next = next;
e.next = null; // Help GC
e.value = null; // " "
size--;
break;
}
prev = p;
p = next;
}
}
}
/**
* Return the table after first expunging stale entries
*/
private /*@Nullable*/ Entry<K,V>[] getTable() {
expungeStaleEntries();
return table;
}
/**
* Returns the number of key-value mappings in this map.
* This result is a snapshot, and may not reflect unprocessed
* entries that will be removed before next attempted access
* because they are no longer referenced.
*/
public int size() {
if (size == 0)
return 0;
expungeStaleEntries();
return size;
}
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
* This result is a snapshot, and may not reflect unprocessed
* entries that will be removed before next attempted access
* because they are no longer referenced.
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Returns the value to which the specified key is mapped in this weak
* hash map, or <tt>null</tt> if the map contains no mapping for
* this key. A return value of <tt>null</tt> does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it is also
* possible that the map explicitly maps the key to <tt>null</tt>. The
* <tt>containsKey</tt> method may be used to distinguish these two
* cases.
*
* @param key the key whose associated value is to be returned.
* @return the value to which this map maps the specified key, or
* <tt>null</tt> if the map contains no mapping for this key.
* @see #put(Object, Object)
*/
public /*@Nullable*/ V get(/*@Nullable*/ Object key) {
Object k = maskNull(key);
int h = hasher (k);
/*@Nullable*/ Entry<K,V>[] tab = getTable();
int index = indexFor(h, tab.length);
Entry<K,V> e = tab[index];
while (e != null) {
if (e.hash == h && eq(k, e.get()))
return e.value;
e = e.next;
}
return null;
}
/**
* Returns <tt>true</tt> if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
* @return <tt>true</tt> if there is a mapping for <tt>key</tt>;
* <tt>false</tt> otherwise
*/
public boolean containsKey(/*@Nullable*/ Object key) {
return getEntry(key) != null;
}
/**
* Returns the entry associated with the specified key in the HashMap.
* Returns null if the HashMap contains no mapping for this key.
*/
/*@Nullable*/ Entry<K,V> getEntry(/*@Nullable*/ Object key) {
Object k = maskNull(key);
int h = hasher (k);
/*@Nullable*/ Entry<K,V>[] tab = getTable();
int index = indexFor(h, tab.length);
Entry<K,V> e = tab[index];
while (e != null && !(e.hash == h && eq(k, e.get())))
e = e.next;
return e;
}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for this key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated.
* @param value value to be associated with the specified key.
* @return previous value associated with specified key, or <tt>null</tt>
* if there was no mapping for key. A <tt>null</tt> return can
* also indicate that the HashMap previously associated
* <tt>null</tt> with the specified key.
*/
public /*@Nullable*/ V put(K key, V value) {
K k = (K) maskNull(key);
int h = System.identityHashCode (k);
/*@Nullable*/ Entry<K,V>[] tab = getTable();
int i = indexFor(h, tab.length);
for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
if (h == e.hash && eq(k, e.get())) {
V oldValue = e.value;
if (value != oldValue)
e.value = value;
return oldValue;
}
}
modCount++;
Entry<K,V> e = tab[i];
tab[i] = new Entry<K,V>(k, value, queue, h, e);
if (++size >= threshold)
resize(tab.length * 2);
return null;
}
/**
* Rehashes the contents of this map into a new array with a
* larger capacity. This method is called automatically when the
* number of keys in this map reaches its threshold.
*
* If current capacity is MAXIMUM_CAPACITY, this method does not
* resize the map, but sets threshold to Integer.MAX_VALUE.
* This has the effect of preventing future calls.
*
* @param newCapacity the new capacity, MUST be a power of two;
* must be greater than current capacity unless current
* capacity is MAXIMUM_CAPACITY (in which case value
* is irrelevant).
*/
void resize(int newCapacity) {
/*@Nullable*/ Entry<K,V>[] oldTable = getTable();
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry<K,V>[] newTable = (Entry<K,V>[]) new Entry[newCapacity];
transfer(oldTable, newTable);
table = newTable;
/*
* If ignoring null elements and processing ref queue caused massive
* shrinkage, then restore old table. This should be rare, but avoids
* unbounded expansion of garbage-filled tables.
*/
if (size >= threshold / 2) {
threshold = (int)(newCapacity * loadFactor);
} else {
expungeStaleEntries();
transfer(newTable, oldTable);
table = oldTable;
}
}
/** Transfer all entries from src to dest tables */
private void transfer(/*@Nullable*/ Entry<K,V>[] src, /*@Nullable*/ Entry<K,V>[] dest) {
for (int j = 0; j < src.length; ++j) {
Entry<K,V> e = src[j];
src[j] = null; // Help GC (?)
while (e != null) {
Entry<K,V> next = e.next;
Object key = e.get();
if (key == null) {
e.next = null; // Help GC
e.value = null; // " "
size--;
} else {
int i = indexFor(e.hash, dest.length);
e.next = dest[i];
dest[i] = e;
}
e = next;
}
}
}
/**
* Copies all of the mappings from the specified map to this map These
* mappings will replace any mappings that this map had for any of the
* keys currently in the specified map.<p>
*
* @param m mappings to be stored in this map.
* @throws NullPointerException if the specified map is null.
*/
public void putAll(Map<? extends K, ? extends V> m) {
int numKeysToBeAdded = m.size();
if (numKeysToBeAdded == 0)
return;
/*
* Expand the map if the map if the number of mappings to be added
* is greater than or equal to threshold. This is conservative; the
* obvious condition is (m.size() + size) >= threshold, but this
* condition could result in a map with twice the appropriate capacity,
* if the keys to be added overlap with the keys already in this map.
* By using the conservative calculation, we subject ourself
* to at most one extra resize.
*/
if (numKeysToBeAdded > threshold) {
int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
if (targetCapacity > MAXIMUM_CAPACITY)
targetCapacity = MAXIMUM_CAPACITY;
int newCapacity = table.length;
while (newCapacity < targetCapacity)
newCapacity <<= 1;
if (newCapacity > table.length)
resize(newCapacity);
}
for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<? extends K, ? extends V> e = i.next();
put(e.getKey(), e.getValue());
}
}
/**
* Removes the mapping for this key from this map if present.
*
* @param key key whose mapping is to be removed from the map.
* @return previous value associated with specified key, or <tt>null</tt>
* if there was no mapping for key. A <tt>null</tt> return can
* also indicate that the map previously associated <tt>null</tt>
* with the specified key.
*/
public /*@Nullable*/ V remove(Object key) {
Object k = maskNull(key);
int h = hasher (k);
/*@Nullable*/ Entry<K,V>[] tab = getTable();
int i = indexFor(h, tab.length);
Entry<K,V> prev = tab[i];
Entry<K,V> e = prev;
while (e != null) {
Entry<K,V> next = e.next;
if (h == e.hash && eq(k, e.get())) {
modCount++;
size--;
if (prev == e)
tab[i] = next;
else
prev.next = next;
return e.value;
}
prev = e;
e = next;
}
return null;
}
/** Special version of remove needed by Entry set */
/*@Nullable*/ Entry<K,V> removeMapping(/*@Nullable*/ Object o) {
if (!(o instanceof Map.Entry))
return null;
/*@Nullable*/ Entry<K,V>[] tab = getTable();
Map.Entry entry = (/*@NonNull*/ Map.Entry)o;
Object k = maskNull(entry.getKey());
int h = hasher (k);
int i = indexFor(h, tab.length);
Entry<K,V> prev = tab[i];
Entry<K,V> e = prev;
while (e != null) {
Entry<K,V> next = e.next;
if (h == e.hash && e.equals(entry)) {
modCount++;
size--;
if (prev == e)
tab[i] = next;
else
prev.next = next;
return e;
}
prev = e;
e = next;
}
return null;
}
/**
* Removes all mappings from this map.
*/
public void clear() {
// clear out ref queue. We don't need to expunge entries
// since table is getting cleared.
while (queue.poll() != null)
;
modCount++;
/*@Nullable*/ Entry<K,V>[] tab = table;
for (int i = 0; i < tab.length; ++i)
tab[i] = null; // Help GC (?)
size = 0;
// Allocation of array may have caused GC, which may have caused
// additional entries to go stale. Removing these entries from the
// reference queue will make them eligible for reclamation.
while (queue.poll() != null)
;
}
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value.
*
* @param value value whose presence in this map is to be tested.
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value.
*/
public boolean containsValue(/*@Nullable*/ Object value) {
if (value==null)
return containsNullValue();
/*@Nullable*/ Entry<K,V>[] tab = getTable();
for (int i = tab.length ; i-- > 0 ;)
for (Entry e = tab[i] ; e != null ; e = e.next)
if (value.equals(e.value))
return true;
return false;
}
/**
* Special-case code for containsValue with null argument
*/
private boolean containsNullValue() {
/*@Nullable*/ Entry<K,V>[] tab = getTable();
for (int i = tab.length ; i-- > 0 ;)
for (Entry e = tab[i] ; e != null ; e = e.next)
if (e.value==null)
return true;
return false;
}
/**
* The entries in this hash table extend WeakReference, using its main ref
* field as the key.
*/
private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {
private V value;
private final int hash;
private /*@Nullable*/ Entry<K,V> next;
/**
* Create new entry.
*/
Entry(K key, V value,
ReferenceQueue<K> queue,
int hash, Entry<K,V> next) {
super(key, queue);
this.value = value;
this.hash = hash;
this.next = next;
}
public K getKey() {
return WeakIdentityHashMap.<K>unmaskNull(get());
}
public V getValue() {
return value;
}
public V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public boolean equals(/*@Nullable*/ Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (/*@NonNull*/ Map.Entry)o; // This annotation shouldn't be necessary??
Object k1 = getKey();
Object k2 = e.getKey();
if (eq (k1, k2)) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}
public int hashCode() {
Object k = getKey();
Object v = getValue();
return ((k==null ? 0 : hasher (k)) ^
(v==null ? 0 : v.hashCode()));
}
public String toString() {
return getKey() + "=" + getValue();
}
}
private abstract class HashIterator<T> implements Iterator<T> {
int index;
/*@Nullable*/ Entry<K,V> entry = null;
/*@Nullable*/ Entry<K,V> lastReturned = null;
int expectedModCount = modCount;
/**
* Strong reference needed to avoid disappearance of key
* between hasNext and next
*/
/*@Nullable*/ Object nextKey = null;
/**
* Strong reference needed to avoid disappearance of key
* between nextEntry() and any use of the entry
*/
/*@Nullable*/ Object currentKey = null;
HashIterator() {
index = (size() != 0 ? table.length : 0);
}
public boolean hasNext() {
/*@Nullable*/ Entry<K,V>[] t = table;
while (nextKey == null) {
Entry<K,V> e = entry;
int i = index;
while (e == null && i > 0)
e = t[--i];
entry = e;
index = i;
if (e == null) {
currentKey = null;
return false;
}
nextKey = e.get(); // hold on to key in strong ref
if (nextKey == null)
entry = entry.next;
}
return true;
}
/** The common parts of next() across different types of iterators */
protected Entry<K,V> nextEntry() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (nextKey == null && !hasNext())
throw new NoSuchElementException();
lastReturned = entry;
entry = entry.next;
currentKey = nextKey;
nextKey = null;
return lastReturned;
}
public void remove() {
if (lastReturned == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
WeakIdentityHashMap.this.remove(currentKey);
expectedModCount = modCount;
lastReturned = null;
currentKey = null;
}
}
private class ValueIterator extends HashIterator<V> {
public V next() {
return nextEntry().value;
}
}
private class KeyIterator extends HashIterator<K> {
public K next() {
return nextEntry().getKey();
}
}
private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() {
return nextEntry();
}
}
// Views
private transient /*@Nullable*/ Set<Map.Entry<K,V>> entrySet = null;
private transient volatile /*@Nullable*/ Set<K> our_keySet = null;
/**
* Returns a set view of the keys contained in this map. The set is
* backed by the map, so changes to the map are reflected in the set, and
* vice-versa. The set supports element removal, which removes the
* corresponding mapping from this map, via the <tt>Iterator.remove</tt>,
* <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
* <tt>clear</tt> operations. It does not support the <tt>add</tt> or
* <tt>addAll</tt> operations.
*
* @return a set view of the keys contained in this map.
*/
public Set<K> keySet() {
Set<K> ks = our_keySet;
return (ks != null ? ks : (our_keySet = new KeySet()));
}
private class KeySet extends AbstractSet<K> {
public Iterator<K> iterator() {
return new KeyIterator();
}
public int size() {
return WeakIdentityHashMap.this.size();
}
public boolean contains(/*@Nullable*/ Object o) {
return containsKey(o);
}
public boolean remove(/*@Nullable*/ Object o) {
if (containsKey(o)) {
WeakIdentityHashMap.this.remove(o);
return true;
}
else
return false;
}
public void clear() {
WeakIdentityHashMap.this.clear();
}
public Object[] toArray() {
Collection<K> c = new ArrayList<K>(size());
for (Iterator<K> i = iterator(); i.hasNext(); )
c.add(i.next());
return c.toArray();
}
public <T> T[] toArray(T[] a) {
Collection<K> c = new ArrayList<K>(size());
for (Iterator<K> i = iterator(); i.hasNext(); )
c.add(i.next());
return c.toArray(a);
}
}
transient volatile /*@Nullable*/ Collection<V> our_values = null;
/**
* Returns a collection view of the values contained in this map. The
* collection is backed by the map, so changes to the map are reflected in
* the collection, and vice-versa. The collection supports element
* removal, which removes the corresponding mapping from this map, via the
* <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
* It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the values contained in this map.
*/
public Collection<V> values() {
Collection<V> vs = our_values;
return (vs != null ? vs : (our_values = new Values()));
}
private class Values extends AbstractCollection<V> {
public Iterator<V> iterator() {
return new ValueIterator();
}
public int size() {
return WeakIdentityHashMap.this.size();
}
public boolean contains(/*@Nullable*/ Object o) {
return containsValue(o);
}
public void clear() {
WeakIdentityHashMap.this.clear();
}
public Object[] toArray() {
Collection<V> c = new ArrayList<V>(size());
for (Iterator<V> i = iterator(); i.hasNext(); )
c.add(i.next());
return c.toArray();
}
public <T> T[] toArray(T[] a) {
Collection<V> c = new ArrayList<V>(size());
for (Iterator<V> i = iterator(); i.hasNext(); )
c.add(i.next());
return c.toArray(a);
}
}
/**
* Returns a collection view of the mappings contained in this map. Each
* element in the returned collection is a <tt>Map.Entry</tt>. The
* collection is backed by the map, so changes to the map are reflected in
* the collection, and vice-versa. The collection supports element
* removal, which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
* It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the mappings contained in this map.
* @see java.util.Map.Entry
*/
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es = entrySet;
return (es != null ? es : (entrySet = new EntrySet()));
}
private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
public boolean contains(/*@Nullable*/ Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (/*@NonNull*/ Map.Entry)o;
// Object k = e.getKey();
Entry candidate = getEntry(e.getKey());
return candidate != null && candidate.equals(e);
}
public boolean remove(/*@Nullable*/ Object o) {
return removeMapping(o) != null;
}
public int size() {
return WeakIdentityHashMap.this.size();
}
public void clear() {
WeakIdentityHashMap.this.clear();
}
public Object[] toArray() {
Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>(size());
for (Iterator<Map.Entry<K,V>> i = iterator(); i.hasNext(); )
c.add(new OurSimpleEntry<K,V>(i.next()));
return c.toArray();
}
public <T> T[] toArray(T[] a) {
Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>(size());
for (Iterator<Map.Entry<K,V>> i = iterator(); i.hasNext(); )
c.add(new OurSimpleEntry<K,V>(i.next()));
return c.toArray(a);
}
}
/** Version copied from Abstract Map because it is not public **/
static class OurSimpleEntry<K,V> implements Map.Entry<K,V> {
K key;
V value;
public OurSimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
public OurSimpleEntry(Map.Entry<K,V> e) {
this.key = e.getKey();
this.value = e.getValue();
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(/*@Nullable*/ Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
return WeakIdentityHashMap.eq(key, e.getKey())
&& eq(value, e.getValue());
}
public int hashCode() {
return ((key == null) ? 0 : key.hashCode()) ^
((value == null) ? 0 : value.hashCode());
}
public String toString() {
return key + "=" + value;
}
private static boolean eq(/*@Nullable*/ Object o1, /*@Nullable*/ Object o2) {
return (o1 == null ? o2 == null : o1.equals(o2));
}
}
}
| Java |
package dummy.perf;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import dummy.lib.NativeObject;
import dummy.test.FilterMethodTest;
import dummy.test.FilterNetworkTest;
import dummy.test.SanitizeHTMLTest;
import dummy.test.SecureClassTest;
import dummy.test.TimerTest;
import dummy.test.UserInputTest;
import dummy.test.XSSFilterTest;
import dummy.test.auth.LoginStatusFilterTest;
import dummy.test.boundry.User;
import dummy.test.boundry.UserRegistry;
public class PerformanceTest {
private static final String OUTPUT_DIRECTORY = "perfnone";
private static final String LOAD_CLASSES_FILE = "load_classes.txt";
private static final String CREATE_USERS_FILE = "create_users.txt";
private static final String NATIVE_OBJECTS_FILE = "native.txt";
private static final String USER_INPUT_FILE = "user_input.txt";
private static final String XSS_RETURN_FILE = "xss_return.txt";
private static final String XSS_PARAM_FILE = "xss_param.txt";
private static final String AUTH_FAIL_FILE = "auth_fail.txt";
private static final String SECURE_CLASS_FILE = "secure_class.txt";
private static final String AUDIT_METHOD_FILE = "audit_method.txt";
private static final String TIMER_METHOD_FILE = "timer_method.txt";
public static void runPerformanceTest() {
long lc = loadClasses();
long cu = createUsers(500);
long no = sendNativeObjects(500);
long ui = runUserInput(500);
long xr = runXssReturn(500);
long xp = runXssParam(500);
long af = runAuthFail(500);
long sc = runSecureClass(500);
long am = runAuditMethod(500);
long tm = runTimerMethod(50);
appendToFile(LOAD_CLASSES_FILE, lc);
appendToFile(CREATE_USERS_FILE, cu);
appendToFile(NATIVE_OBJECTS_FILE, no);
appendToFile(USER_INPUT_FILE, ui);
appendToFile(XSS_RETURN_FILE, xr);
appendToFile(XSS_PARAM_FILE, xp);
appendToFile(AUTH_FAIL_FILE, af);
appendToFile(SECURE_CLASS_FILE, sc);
appendToFile(AUDIT_METHOD_FILE, am);
appendToFile(TIMER_METHOD_FILE, tm);
System.out.println("Time to load classes: " + lc + " ms");
System.out.println("Time to create Users: " + cu + " ms");
System.out.println("Time to send objects: " + no + " ms");
System.out.println("Time to run user input test " + ui + " ms");
System.out.println("Time to filter XSS return " + xr + " ms");
System.out.println("Time to filter XSS param " + xp + " ms");
System.out.println("Time to fail auth " + af + " ms");
System.out.println("Time to secure class " + sc + " ms");
System.out.println("Time to audit method " + am + " ms");
System.out.println("Time to run timer " + tm + " ms");
}
private static long loadClasses() {
System.out.println("Loading classes...");
long start = System.currentTimeMillis();
@SuppressWarnings("unused")
User user = UserRegistry.addUser("temp", "temp");
@SuppressWarnings("unused")
NativeObject no = new NativeObject();
FilterNetworkTest.sendObj(new Object());
UserInputTest.doTest();
LoginStatusFilterTest.doTest();
SecureClassTest.doTest();
FilterMethodTest.filterMe("foo");
TimerTest.doPerfTest();
long end = System.currentTimeMillis();
System.out.println("...finished loading classes");
return end - start;
}
private static long createUsers(int n) {
System.out.println("Starting createUsers...");
long start = System.currentTimeMillis();
for (int i = 0 ; i < n ; i++) {
UserRegistry.addUser("user"+i, "password"+i);
}
long end = System.currentTimeMillis();
System.out.println("...ending createUsers");
return end - start;
}
private static long sendNativeObjects(int n) {
System.out.println("Sending objects...");
long start = System.currentTimeMillis();
for (int i = 0 ; i < n ; i++) {
try {
FilterNetworkTest.sendObj(new NativeObject());
}
catch (Exception ex) {
//Okay
}
}
long end = System.currentTimeMillis();
System.out.println("...finished sending");
return end - start;
}
private static long runUserInput(int n) {
System.out.println("Simulating user input...");
long start = System.currentTimeMillis();
for (int i = 0 ; i < n ; i++) {
UserInputTest.doTest();
}
long end = System.currentTimeMillis();
System.out.println("...finished simulation");
return end - start;
}
private static long runXssReturn(int n) {
System.out.println("Running XSS return...");
long start = System.currentTimeMillis();
for (int i = 0 ; i < n ; i++) {
SanitizeHTMLTest.doTest();
}
long end = System.currentTimeMillis();
System.out.println("...stopping XSS return");
return end - start;
}
private static long runXssParam(int n) {
System.out.println("Running XSS param...");
long start = System.currentTimeMillis();
for (int i = 0 ; i < n ; i++) {
XSSFilterTest.doTest();
}
long end = System.currentTimeMillis();
System.out.println("...stopping XSS param");
return end - start;
}
private static long runAuthFail(int n) {
System.out.println("Running auth fail...");
long start = System.currentTimeMillis();
for (int i = 0 ; i < n ; i++) {
LoginStatusFilterTest.doTest();
}
long end = System.currentTimeMillis();
System.out.println("...stopping auth fail");
return end - start;
}
private static long runSecureClass(int n) {
System.out.println("Running secure class...");
long start = System.currentTimeMillis();
for (int i = 0 ; i < n ; i++) {
SecureClassTest.doTest();
}
long end = System.currentTimeMillis();
System.out.println("...stopping secure class");
return end - start;
}
private static long runAuditMethod(int n) {
System.out.println("Running audit method...");
long start = System.currentTimeMillis();
for (int i = 0 ; i < n ; i++) {
FilterMethodTest.filterMe("foo");
}
long end = System.currentTimeMillis();
System.out.println("...stopping audit method");
return end - start;
}
private static long runTimerMethod(int n) {
System.out.println("Running timer method...");
long start = System.currentTimeMillis();
for (int i = 0 ; i < n ; i++) {
TimerTest.doPerfTest();
}
long end = System.currentTimeMillis();
System.out.println("...stopping timer method");
return end - start;
}
/****** Util functions ******/
private static void appendToFile(String fileName, long l) {
try {
File file = new File(OUTPUT_DIRECTORY+"/"+fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(l+" ");
writer.flush();
writer.close();
} catch (IOException e) {
System.out.println("Could not append to file " + fileName);
return;
}
}
}
| Java |
package dummy.perf;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;
public class AverageMain {
private static final String AVERAGE_FILE = "averagenone.txt";
private static final String INPUT_DIRECTORY = "perfnone";
public static void main(String[] args) {
//Find the perf directory
File dir = new File(INPUT_DIRECTORY);
//Create a PerfRun object for each file in the directory
LinkedList<PerfRun> runs = new LinkedList<PerfRun>();
for (File f : dir.listFiles()) {
//Ignore .svn
if (f.getName().contains("svn")) continue;
try {
Scanner scan = new Scanner(f);
long sum = 0;
double avg = 0.0, dev = 0.0;
//Add all longs to list, compute running sum
LinkedList<Long> list = new LinkedList<Long>();
while(scan.hasNextLong()) {
long curr = scan.nextLong();
list.add(curr);
sum += curr;
}
//Compute average
if (list.size() > 0)
avg = (double)sum / (double)list.size();
//Compute std dev
double dev_sum = 0.0;
for (Long curr : list) {
dev_sum += Math.pow(curr - avg, 2);
}
if (list.size() > 0)
dev = Math.sqrt(dev_sum/(list.size()-1));
//Add new PerfRun
runs.add(new PerfRun(list.size(), avg, dev, f.getPath()));
}
catch (IOException e) {
System.err.println("Could not create Scanner for " + f.getAbsolutePath());
continue;
}
}
try {
File average = new File(AVERAGE_FILE);
if (!average.exists()) {
average.createNewFile();
}
FileWriter writer = new FileWriter(average);
for (PerfRun pr : runs) {
writer.append(pr.toString() + "\n");
}
writer.flush();
writer.close();
}
catch (IOException e) {
System.out.println("Could not write to file " + AVERAGE_FILE);
}
}
private static class PerfRun {
int count;
double avg, dev;
String name;
public PerfRun(int c, double a, double d, String n) {
count = c; avg = a; dev = d; name = n;
}
public String toString() {
StringBuilder msg = new StringBuilder();
msg.append("In file: " + name + "\n");
msg.append("\t" + count + " runs\n");
msg.append(String.format("\t%8s =%10.4f ms\n", "Avg", avg));
msg.append(String.format("\t%8s =%10.4f", "StdDev", dev));
return msg.toString();
}
}
}
| Java |
package dummy.lib;
//import org.annoflow.filter.Filter;
//Annotate secure policy here.
public class PrivateDataSink
{
private String password = "foo";
//@Filter(type=SecureBoundary.class)
public String getPassword()
{
return password;
}
}
| Java |
package dummy.lib;
import org.annoflow.policy.TopSecretPolicy;
import org.annoflow.policy.TopSecret;
import org.annoflow.policy.Policy;
@TopSecret
public class TSPassword
{
@Policy(policy = TopSecretPolicy.class)
private String password;
public TSPassword(String pw)
{
this.password = pw;
}
public String getPassword()
{
return password;
}
public String toString()
{
return password;
}
}
| Java |
package dummy.lib;
import org.annoflow.policy.Policy;
import org.annoflow.policy.UserInputPolicy;
public class UserForm {
private int id;
@Policy(policy=UserInputPolicy.class)
private String name;
@Policy(policy=UserInputPolicy.class)
private String greeting;
public UserForm(int i, String n, String g) {
this.id = i;
this.name = n;
this.greeting = g;
}
public String getName() {
return name;
}
public String getGreeting() {
return greeting;
}
protected int getId() {
return id;
}
public String toString() {
return greeting + " " + name;
}
}
| Java |
package dummy.lib;
import org.annoflow.policy.AnchoredPolicy;
import org.annoflow.policy.Policy;
@Policy(policy=AnchoredPolicy.class)
public class NativeObject {
private int x;
public NativeObject() {
this.x = 0;
}
public NativeObject(int x) {
this.x = x;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
| Java |
package dummy.test.locality;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Layer3 {
public static void execute() {
File foo = new File("remote/file");
try {
FileReader reader = new FileReader(foo);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
| Java |
package dummy.test.locality;
import org.annoflow.policy.*;
import org.annoflow.policy.locality.*;
@Policy(policy=LocalizeClassPolicy.class)
public class Layer2 {
public static void execute()
{
Layer3.execute();
}
}
| Java |
package dummy.test.locality;
public class Layer1 {
public static void skipLayer2()
{
Layer3.execute();
}
public static void execute()
{
Layer2.execute();
}
}
| Java |
package dummy.test;
import org.annoflow.policy.Policy;
import org.annoflow.policy.TopSecretPolicy;
@Policy(policy = TopSecretPolicy.class)
public class TSPassword
{
@Policy(policy = TopSecretPolicy.class)
private String password;
public TSPassword()
{
this.password = "password";
}
public String getPassword()
{
return password;
}
public String toString()
{
return password;
}
}
| Java |
package dummy.test.boundry;
import java.util.HashMap;
import java.util.Map;
import org.annoflow.policy.Policy;
import org.annoflow.policy.boundry.SecureClassPolicy;
@Policy(policy=SecureClassPolicy.class)
public class UserRegistry {
public static Map<String,User> userProfiles;
public static User getUser(String userName)
{
return userProfiles.get(userName);
}
static
{
userProfiles = new HashMap<String,User>();
userProfiles.put("Mike",new User("Mike", "foo"));
userProfiles.put("John",new User("John", "foo"));
userProfiles.put("Ali",new User("Ali", "foo"));
userProfiles.put("Sylvia",new User("Sylvia", "foo"));
userProfiles.put("Alex",new User("Alex", "foo"));
userProfiles.put("Josh",new User("Josh", "foo"));
userProfiles.put("Richard",new User("Richard", "foo"));
}
public static boolean requestPasswordChange(User internalUser, String oldPassword, String newPassword)
{
if(internalUser.getPassword().equals(oldPassword))
{
internalUser.setPassword(newPassword);
return true;
}
return false;
}
public static User authentcateUser(String userName, String password) {
User profile = userProfiles.get(userName);
if(profile.getPassword().equals(password))
{
return profile;
}
return null;
}
public static User addUser(String userName, String password) {
User user = new User(userName, password);
userProfiles.put(userName, user);
return user;
}
}
| Java |
package dummy.test.boundry;
import org.annoflow.filter.Filter;
import org.annoflow.filter.boundry.*;
import org.annoflow.policy.Policy;
import org.annoflow.policy.boundry.*;
@Policy(policy=SecureClassPolicy.class)
public class User {
private String userName;
private String password;
public User(String uName, String pass) {
userName = uName;
password = pass;
}
@Filter(type=SecureMethodFilter.class)
public String getPassword()
{
return password;
}
@Filter(type=MixFilter.class)
public void setPassword(String password)
{
this.password = password;
}
public String getUserName()
{
return userName;
}
}
| Java |
package dummy.test.boundry;
import org.annoflow.policy.Policy;
import org.annoflow.policy.boundry.InsecureClassPolicy;
@Policy(policy=InsecureClassPolicy.class)
public class ClientApp {
User newUser;
public void createUser()
{
newUser = new User("Mike","foo");
}
public String getPassword()
{
newUser = new User("Mike","foo");
return newUser.getPassword();
}
public void checkOnUser()
{
newUser = UserRegistry.getUser("Mike");
newUser.getPassword();
}
public void requestAuthenticate()
{
newUser = UserRegistry.authentcateUser("Mike","foo");
assert(newUser != null);
}
public void resetSecurity()
{
newUser = UserRegistry.getUser("Mike");
newUser.setPassword("*****");
newUser.getPassword();
}
public void preserveSecurity()
{
newUser = UserRegistry.getUser("Mike");
UserRegistry.requestPasswordChange(newUser, "foo", "bar");
newUser.getPassword();
}
}
| Java |
import org.annoflow.filter.AuditFilter;
import org.annoflow.policy.Policy;
import org.annoflow.policy.boundry.SecureClassPolicy;
import org.annoflow.filter.Filter;
import org.annoflow.filter.auth.*;
import student.web.internal.SharedPersistenceMap;
@Policy(policy=SecureClassPolicy.class)
public class UserRegistry {
private static SharedPersistenceMap<User> userMap = new SharedPersistenceMap<User>(User.class);
@Filter(type=NewUserFilter.class)
public static User createUser(String userName, String password) {
if(userMap.get(userName) != null)
{
return null;
}
User newUser = new User(password);
userMap.put(userName, newUser);
return newUser;
}
public static User authenticateUser(String userName, String password) {
User lookUp = userMap.get(userName);
if (lookUp != null && lookUp.getPassword().equals(password))
return lookUp;
return null;
}
public static void updateUser(User user)
{
userMap.put(user.getName(), user);
}
}
| Java |
public interface ZHTMLTestClass {
public void loadClasses();
public void doTest(int iterations);
}
| Java |
import org.annoflow.policy.Policy;
import org.annoflow.policy.boundry.SecureClassPolicy;
import org.annoflow.filter.*;
import org.annoflow.filter.boundry.*;
import org.annoflow.filter.xss.*;
@Policy(policy=SecureClassPolicy.class)
public class User {
private String name;
private String imageURL;
private int age;
private String schoolLink;
private String schoolName;
private String password;
public User(String password) {
init();
this.password = password;
}
public User() {
init();
}
private void init() {
name = "Mike";
imageURL = "HokieBird.jpg";
age = 10;
schoolLink = "http://vt.edu";
schoolName = "Virginia Tech";
password = "foobar";
}
public String getName() {
return name;
}
public String getImage() {
return imageURL;
}
public int getAge() {
return age;
}
public String getSchoolLink() {
return "<a href=\"" + schoolLink + "\" style=\"font-size: 10pt\">"
+ getSchoolName() + "</a>";
}
@Filter(type=SanitizeHTMLFilter.class)
public String getSchoolName() {
return schoolName;
}
public String getSchoolAddress() {
return schoolLink;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public void setSchoolAddress(String schoolAddress) {
this.schoolLink = schoolAddress;
}
@Filter(type=SecureMethodFilter.class)
public String getPassword() {
return password;
}
@Filter(type=SecureMethodFilter.class)
public String toString() {
return name + ":" + password;
}
}
| Java |
import org.annoflow.filter.sqli.*;
import org.annoflow.policy.Policy;
import org.annoflow.policy.boundry.SecureClassPolicy;
import org.zkoss.zk.ui.Executions;
import org.annoflow.filter.Filter;
import org.annoflow.filter.auth.*;
import student.web.Application;
import student.web.internal.CurrentUserMap;
import student.web.internal.SharedPersistenceMap;
public class LoginApp
{
CurrentUserMap<User> currentUser = new CurrentUserMap<User>(User.class);
SharedPersistenceMap<User> users = new SharedPersistenceMap<User>(User.class);
public LoginApp()
{
}
private String response = "";
@Filter(type=LoginStatusFilter.class)
public void markFail(String message)
{
response=message;
}
@Filter(type=SQLBoundFilter.class)
public boolean login(String userName, String password)
{
User user = UserRegistry.authenticateUser(userName,password);
if (user != null)
{
currentUser.setCurrentUser(user);
Executions.sendRedirect("app.zhtml");
return true;
}
markFail("Error Bad Credentials");
return false;
}
public String getLoginResponse()
{
return response;
}
@Filter(type=SQLBoundFilter.class)
public boolean createNewUser(String userName, String password)
{
User newUser = UserRegistry.createUser(userName,password);
if(newUser == null)
{
markFail("Could Not Create New User");
return false;
}
currentUser.setCurrentUser(newUser);
Executions.sendRedirect("app.zhtml");
return true;
}
}
| Java |
import org.annoflow.audit.Logger;
import student.web.Application;
import student.web.internal.CurrentUserMap;
import student.web.internal.SharedPersistenceMap;
public class FaceApp
{
CurrentUserMap<User> currentUser = new CurrentUserMap<User>(User.class);
SharedPersistenceMap<User> users = new SharedPersistenceMap<User>(User.class);
public FaceApp()
{
//super("mjw87-app");
}
public boolean login(String userName, String password)
{
if (userName.equals("mjw87") && password.equals("foobar"))
{
currentUser.setCurrentUser(new User());
return true;
}
return false;
}
public void logout()
{
}
public boolean isLoggedIn()
{
return currentUser.getCurrentUser() != null;
}
public User getUser()
{
User current = currentUser.getCurrentUser();
return current;
}
}
| Java |
import student.web.internal.CurrentUserMap;
import student.web.internal.SharedPersistenceMap;
public class EditApp
{
CurrentUserMap<User> currentUser = new CurrentUserMap<User>(User.class);
SharedPersistenceMap<User> users = new SharedPersistenceMap<User>(User.class);
public EditApp()
{
}
public User getCurrentUser()
{
return currentUser.getCurrentUser();
}
public boolean login(String userName, String password)
{
return false;
}
public void saveProfile(User user)
{
UserRegistry.updateUser(user);
currentUser.setCurrentUser(user);
}
public void undoChanges()
{
users.get(currentUser.getCurrentUser().getName());
// User user = currentUser.getCurrentUser();
// currentUser.setCurrentUser(user);
}
}
| Java |
package cloudspace.vm.javassist;
import java.util.List;
import org.annoflow.filter.Filter;
import org.annoflow.filter.FilterPoint;
import org.annoflow.policy.PolicyType;
import org.annoflow.policy.Policy;
import org.annoflow.policy.TopSecret;
import org.apache.log4j.Logger;
import cloudspace.vm.VM;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.Translator;
public class AnnoTranslator implements Translator {
private AnnoCustomExprEditor cusExpr;
private Logger logger = Logger.getLogger(AnnoTranslator.class);
public AnnoTranslator(ConfigParser current) {
List<CommandInterface> editConfigs = current.getCommands();
cusExpr = new AnnoCustomExprEditor(editConfigs);
}
@Override
public void onLoad(ClassPool pool, String className)
throws NotFoundException, CannotCompileException {
// logger.info("Loading Class " + className);
if (VM.currentVM().isLocalClass(className)) {
CtClass clazz = pool.get(className);
try {
rewriteFilters(clazz);
addPolicies(clazz, pool);
cusExpr.staticEdits(clazz);
if (!clazz.isFrozen()) {
clazz.instrument(cusExpr);
}
} catch (ClassNotFoundException e) {
logger.error(e);
}
}
}
private void rewriteFilters(CtClass clazz) throws ClassNotFoundException {
try {
for (CtMethod method : clazz.getDeclaredMethods()) {
for (Object annotation : method.getAnnotations()) {
if (annotation instanceof Filter) {
logger.info("Found Filter annotation on "
+ method.getName() + " in class "
+ clazz.getName());
Filter filterAnno = (Filter) annotation;
String annoType = filterAnno.type().getName();
@SuppressWarnings("unchecked")
Class<FilterPoint> annoClazz = (Class<FilterPoint>) Class
.forName(annoType);
FilterPoint fPoint = annoClazz.newInstance();
String filterCode = fPoint.getFilterCode();
String returnFilterCode = fPoint.getReturnFilterCode();
// System.err.println(filterCode);
if (filterCode != null)
method.insertBefore("org.annoflow.audit.ContextTracker.getInstance().setFilterContext($class);"+filterCode+"org.annoflow.audit.ContextTracker.getInstance().clear();");
if (returnFilterCode != null)
method.insertAfter("org.annoflow.audit.ContextTracker.getInstance().setFilterContext($class);"+returnFilterCode+"org.annoflow.audit.ContextTracker.getInstance().clear();", true); //Treat as "finally" block
}
}
}
} catch (IllegalAccessException e) {
logger.error("Could not call filter default constructor", e);
} catch (InstantiationException e) {
logger.error("Exception thrown inside of constructor", e);
} catch (CannotCompileException e) {
logger.error("The replacement text is no good!", e);
}
}
private void addPolicies(CtClass clazz, ClassPool pool) {
try {
for (Object annotation : clazz.getAnnotations()) {
String policyClass = null;
if (annotation instanceof Policy) {
logger.info("Found Policy annotation on " + clazz.getName()
+ " class");
Policy policy = (Policy) annotation;
policyClass = policy.policy().getName();
} else if (annotation instanceof TopSecret) {
policyClass = "org.annoflow.policy.TopSecretPolicy";
logger.info("Found TopSecret annotation on "
+ clazz.getName() + " class");
}
if (policyClass != null) {
@SuppressWarnings("unchecked")
Class<PolicyType> pClazz = (Class<PolicyType>) Class
.forName(policyClass);
String src = pClazz.newInstance().getPolicyCode();
CtConstructor staticConstructor = clazz
.makeClassInitializer();
if (staticConstructor != null) {
staticConstructor.insertBefore(src);
}
// for (CtConstructor construct : clazz.getConstructors()) {
// // System.err.println(src);
// construct.insertBefore(src);
// }
}
}
} catch (IllegalAccessException e) {
logger.error("Could not call policy default constructor", e);
} catch (InstantiationException e) {
logger.error("Exception thrown inside of constructor", e);
} catch (ClassNotFoundException e) {
logger.error("Could not find specified class", e);
} catch (CannotCompileException e) {
logger.error(
"Could not compile the modifications for Policy cutin", e);
} catch (SecurityException e) {
logger.error("Could not construct a policy object for the class", e);
} catch (IllegalArgumentException e) {
logger.error("The arguments to the constructor are incorrect", e);
}
}
@Override
public void start(ClassPool pool) throws NotFoundException,
CannotCompileException {
}
}
| Java |
package cloudspace.vm;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javassist.ClassPool;
import javassist.Loader;
import javassist.NotFoundException;
import org.apache.log4j.Logger;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import bsh.Interpreter;
import cloudspace.vm.filesystem.ProjectSpec;
import cloudspace.vm.io.console.InfoStream;
import cloudspace.vm.io.console.SystemStreamMultiplexer;
import cloudspace.vm.javassist.JavassistBootloader;
import cloudspace.vm.javassist.MalformedConfigurationException;
//TODO: implement a strategy for handling memory management
/**
* The Class VM. This is a basic Cloudspace Virtual Machine. This virtual
* Machine provides shared information about the specific virtual machine to
* every virtual machine context created in this context. This virtual machine
* holds information about. local classes, local loader, delegated classes,
* standard output streams, and parent loaders. There is one of these per
* instance of a virtual machine.
*/
public class VM
{
private Map<String, Object> localObjects = new HashMap<String,Object>();
/**
* An exception that occurs when a thread requests a VM and there is no vm
* tagged in the threadLocal.
*
* @author mjw87
*
*/
public static class NoVmException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = 524965398230936313L;
public NoVmException(String msg)
{
super(msg);
}
}
protected static Logger logger = Logger.getLogger(VM.class);
// -------------------------------------------------------------------------
/**
* The Class LoggedClassPool. This class represents a Logged class pool that
* can detect updates to the class files stored internally.
*/
private class LoggedClassPool extends ClassPool
{
List<File> currentClassPath;
/** The logged class path entries. */
private long timeStamp;
public LoggedClassPool(ClassPool parent)
{
super(parent);
init();
}
/**
* Initializes the class pool's variables.
*/
private void init()
{
this.logUpdate();
}
/**
* This private method recurses through the classpath entries to log
* time stamps for every file in the class path.
*
* @param classPathDir
* the class path directory to recurse and log.
*/
private List<File> recurseClassPathEntry(File root)
{
List<File> flattenList = new ArrayList<File>();
File[] dirList = root.listFiles();
if (dirList != null)
{
for (File classPathEntry : dirList)
{
if (classPathEntry.isDirectory())
{
flattenList.addAll(recurseClassPathEntry(classPathEntry));
}
else
{
flattenList.add(classPathEntry);
}
}
}
return flattenList;
}
/**
* Checks if the class pool has been updated
*
* @return true, if is updated
*/
public boolean isUpdated()
{
for (File oldFiles : currentClassPath)
{
if (!oldFiles.exists())
return true;
}
List<File> flatList = recurseClassPathEntry(localRoot);
for (File lFile : flatList)
{
if (lFile.lastModified() > timeStamp)
{
return true;
}
}
return false;
}
public void logUpdate()
{
timeStamp = java.util.Calendar.getInstance().getTime().getTime();
currentClassPath = this.recurseClassPathEntry(localRoot);
}
}
/**
* This set keeps track of all of the desktops associated with this virtual
* machine.
*/
//private Set<String> desktops;
/**
* The local root directory for the virtual machine.
*/
private File localRoot;
/**
* The Enum PrinterType.
*/
public enum PrinterType
{
/** The OUT. */
OUT,
/** The ERROR. */
ERROR
};
private String loaderStamp;
/**
* The protected Info Stream tags for VM provided streams.
*/
public static final String standardOutTag = "Standard Out";
public static final String standardErrorTag = "Standard Error";
public static final String logTag = "CloudSpace Logs";
/**
* The Standard Out stream and Printer. The printer is pre wrapped just for
* convenience this allows a user to perform VM.out to print to the VM
* specfic standard out
*/
private final InfoStream stdOut = new InfoStream(standardOutTag);
public final PrintStream out = new PrintStream(stdOut);
/** See above for reasoning */
private final InfoStream stdErr = new InfoStream(standardErrorTag);
public final PrintStream err = new PrintStream(stdErr);
private final InfoStream stdLog = new InfoStream(logTag);
public final PrintStream log = new PrintStream(stdLog);
private Lock eventLock = new ReentrantLock();
/** The mapping from local Directories (unique to each VM) to cloudspaceVMs. */
private static Map<String, VM> directoryToVM = new HashMap<String, VM>();
/**
* The current loader for the VM. This is updated when classes have been
* changed in the classpool.
*/
private Loader vmLoader;
private LoggedClassPool vmPool;
/** The thread current vm. */
private static ThreadLocal<VM> threadCurrentVM = new ThreadLocal<VM>();
private static ThreadLocal<ClassLoader> threadOldLoader = new ThreadLocal<ClassLoader>();
/**
* Enter this VM and associated current desktop with it.
*/
public void lockVM()
{
eventLock.lock();
}
/**
* This silently sets the currentVM it will not take ownership of the VM!
* BECAREFUL!!
*
*/
public void enter()
{
enter0();
}
/**
* Enter this VM and associate desktop with id 'dID' with the VM.
*/
private void enter0()
{
threadCurrentVM.set(this);
threadOldLoader.set(Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(this.getLoader());
//desktopID.set(dID);
}
/**
* Leave this VM.
*/
public void unlockVM()
{
eventLock.unlock();
}
/**
* This silently leaves the VM's context.
* BECAREFUL!
*
*/
public static void leave()
{
leave0();
}
private static void leave0()
{
threadCurrentVM.set(null);
ClassLoader loader = threadOldLoader.get();
threadOldLoader.set(null);
Thread.currentThread().setContextClassLoader(loader);
}
/**
* Gets the current VM.
*
* @return the current VM
*/
public static VM currentVM()
{
try
{
return threadCurrentVM.get();
}
catch (NullPointerException e)
{
throw new NoVmException("There is no VM associated with this thread");
}
}
/**
* This method looks up the current VM context a class is acting in. It uses
* ZK desktop and page information to determine which vm instance a thread
* is acting in.
*
* Will not enter VM.
*
* @return the instance of the vm associated with the current desktop's
* basedir
*/
public static VM lookupVM()
{
String currentPage = Executions.getCurrent().getDesktop().getRequestPath();
String currentDir = getBaseDir(currentPage);
String localRoot = Executions.getCurrent().getDesktop().getWebApp().getRealPath(currentDir);
return lookupVM(localRoot);
}
/**
* Look up VM associated with 'baseDir', creating it if necessary.
*/
public static VM lookupVM(String baseDir)
{
String projectBaseDir = ProjectSpec.getBaseProjectDir(baseDir);
VM vm = directoryToVM.get(projectBaseDir);
logger.info("Looking up "+baseDir+" as "+projectBaseDir);
if (vm == null)
{
vm = new VM(projectBaseDir);
vm.addEventListener(new VM.EventListenerAdapter() {
@Override
public void onClassReload()
{
/*
* We must reset session attributes if classes are reloaded.
* Determine if 'app-store' is sufficient or not.
*/
Session session = Sessions.getCurrent();
for (Object attrName : session.getAttributes().keySet())
{
if (((String) attrName).contains("app-store"))
{
logger.info("onClassReload: Clearing session attribute: "
+ (String) attrName);
// System.out.println("onClassReload: Clearing session attribute: "
// + (String) attrName);
session.removeAttribute((String) attrName);
}
}
}
});
directoryToVM.put(projectBaseDir, vm);
}
return vm;
}
public boolean bounceLoader = false;
/**
* This private member requests an update to the Class Loader registered to
* this virtual Machine. The update will only happen if a class in the class
* pool has been updated.
*/
private void updateLoader()
{
synchronized (vmPool)
{
if (vmPool.isUpdated() || bounceLoader)
{
logger.info("Updating classes.");
updateLoader0();
bounceLoader = false;
}
}
}
/**
* Gets the base dir of a page. This method assumes a
* www.webpage.domain/<UNIQUE PAGE TAG>/...... If the format differs from
* this, cloudspace will not work.
*
* @param currentPage
* string representing the current request path.
*
* @return the base dir representation of a page request.
*/
private static String getBaseDir(String currentPage)
{
int index = currentPage.indexOf('/');
int index2 = currentPage.lastIndexOf("/");
String callPath = currentPage.substring(index, index2);
return callPath;
}
/**
* Instantiates a new cloudspace vm. Using a localRoot and desktop ID.
*
* @param vmContext
* the desk id
* @param localRoot
* the local root
*/
public VM(String projectBaseDir)
{
//desktops = new HashSet<String>();
localRoot = new File(projectBaseDir);
logger.info("Creating new Virtual Machine for "+localRoot.getPath()+" on request path "+projectBaseDir);
updateLoader0();
}
public void updateLoader0()
{
this.log.println("Source code has changed, server has been updated!");
final ClassLoader parentLoader = this.getClass().getClassLoader();
ClassPool proxyPool = JavassistBootloader.getProxyPool();
vmPool = new LoggedClassPool(proxyPool);
/* define locations in which rewritable .class files are */
try
{
if (Executions.getCurrent() != null)
{
logger.info("("+localRoot.getPath()+") Adding /WEB-INF/pagelib/ to classpath");
vmPool.appendClassPath(Executions.getCurrent().getDesktop().getWebApp()
.getRealPath("/WEB-INF/pagelib/")+"*");
}
logger.info("("+localRoot.getPath()+") Adding local directory to classpath");
vmPool.appendClassPath(localRoot.getAbsolutePath());
logger.info("("+localRoot.getPath()+") Adding local directory jars to classpath");
vmPool.appendClassPath(localRoot + File.separator + "*");
logger.info("("+localRoot.getPath()+") Adding classes directory within the local directory to classpath");
vmPool.appendClassPath(localRoot + File.separator + "classes" + File.separator + "*");
logger.info("("+localRoot.getPath()+") Adding System classpath to classpath");
vmPool.appendSystemPath();
}
catch (NotFoundException e)
{
logger.error("Class pool could not initialize because of missing directories",e);
}
vmPool.logUpdate();
/* always attempt to delegate to parent first */
vmLoader = new Loader(parentLoader, vmPool) {
protected Class<?> loadClassByDelegation(String clazzName) throws ClassNotFoundException
{
if (clazzName.startsWith("_test."))
{
return null;
}
try
{
return delegateToParent(clazzName);
}
catch (ClassNotFoundException ncdef)
{
return null;
}
}
};
loaderStamp = Calendar.getInstance().getTime().toString();
try
{
JavassistBootloader.translateClasses(vmLoader, vmPool);
}
catch (MalformedConfigurationException e)
{
logger.error("Configuration problem in Javassist config",e);
}
runLoaderListeners();
}
/**
* Prepares an interpreter for use in the current context.
*
* @param ip
*/
public void prepareInterpreter(Interpreter ip)
{
updateLoader();
ip.setClassLoader(vmLoader);
}
/**
* Gets the Info Stream operating as a backend to System.out.
*
* @return InfoStream System.out
*/
public InfoStream getStdOut()
{
return stdOut;
}
/**
* Gets the Info Stream operating as a backend to System.err.
*
* @return InfoStream System.err
*/
public InfoStream getError()
{
return stdErr;
}
/**
* This gets a VM hardwired stream according to a printer type. Currently,
* only system.out and system.err are hardwired.
*
* @param streamID
* @return the protected VM stream corresponding to the passed printer type.
*/
public PrintStream getStream(PrinterType streamID)
{
switch (streamID)
{
case OUT:
return out;
case ERROR:
return err;
default:
return null;
}
}
/**
* Get the unique local root for this VM. A VM only has one local root and
* it does not share this local root with any other VM.
*
* @return The root directory for the VM.
*/
public String getLocalRoot()
{
return localRoot.getAbsolutePath();
}
/**
* Gets the class pool for this VM
*
* @return the VM's class pool
*/
public ClassPool getClassPool()
{
return vmPool;
}
public boolean isLocalClass(final String classname)
{
return vmPool.find(classname) != null || classname.startsWith("_test.wrap");
}
/**
* Gets the class loader used for all bean shell interpreters in this VM's
* Context
*
* @return the current Context's class loader
*/
public Loader getLoader()
{
return vmLoader;
}
// Static init block. This sets up the SystemStreamMultiplexer to start
// intercepting system.out and system.err
static
{
if (!(System.out instanceof SystemStreamMultiplexer))
{
SystemStreamMultiplexer ssm = new SystemStreamMultiplexer(System.out);
ssm.setStream(PrinterType.OUT);
System.setOut(ssm);
}
if (!(System.err instanceof SystemStreamMultiplexer))
{
SystemStreamMultiplexer ssmErr = new SystemStreamMultiplexer(System.err);
ssmErr.setStream(PrinterType.ERROR);
System.setErr(ssmErr);
}
}
/**
* Gets the Info Stream representing the CloudSpace Log.
*
* @return the protected InfoStream Log
*/
public InfoStream getLog()
{
return stdLog;
}
/**
* Get the last time the loader was initialized.
*
* @return the current Loader timestamp
*/
public String getLoaderTime()
{
return loaderStamp;
}
/**
* Registers a desktop to the current VM.
*
* @param dID
* Desktop ID.
*/
/*public void addDesktop(String dID)
{
if(!desktops.contains(dID))
desktops.add(dID);
}*/
/**
* de registers a Desktop ID from the Virtual Machine.
*
* @param dID
* the Desktop ID to remove.
*/
/* public void removeDesktop(String dID)
{
desktops.remove(dID);
}*/
/**
* Gets the number desktops registered to this VM.
*
* @return the number desktops
*/
/* public int getNumberDesktops()
{
return desktops.size();
}*/
/**
* A class listeners for VM events must implement.
*/
public interface EventListener
{
/**
* Called if VM reloads user classes.
*/
public void onClassReload();
/* Add others here. */
}
/**
* An adapter class for VM.EventListener
*/
public static abstract class EventListenerAdapter implements EventListener
{
@Override
public void onClassReload()
{
}
}
private List<EventListener> vmListeners = new ArrayList<EventListener>();
/**
* Add an VM event listener.
*/
public void addEventListener(EventListener listener)
{
vmListeners.add(listener);
}
/**
* Remove an VM event listener.
*/
public void removeEventListener(EventListener listener)
{
vmListeners.remove(listener);
}
private void runLoaderListeners()
{
for (EventListener l : vmListeners)
{
l.onClassReload();
}
}
public void setLocalObject(String key, Object obj)
{
localObjects.put(key, obj);
}
public Object getLocalObject(String key)
{
return localObjects.get(key);
}
}
| Java |
package cloudspace.vm.javassist;
import java.lang.annotation.Annotation;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.expr.Cast;
import javassist.expr.ConstructorCall;
import javassist.expr.Expr;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
import javassist.expr.Handler;
import javassist.expr.Instanceof;
import javassist.expr.MethodCall;
import javassist.expr.NewArray;
import javassist.expr.NewExpr;
import cloudspace.vm.javassist.AbstractCommand.SignatureType;
import org.apache.log4j.Logger;
import org.annoflow.filter.FilterPoint;
import org.annoflow.policy.PolicyType;
import org.annoflow.policy.Policy;
/**
* The Class CustomExprEditor. This class is responsible for actually editing
* the
*/
public class AnnoCustomExprEditor extends ExprEditor {
protected Logger logger = Logger.getLogger(CustomExprEditor.class);
private abstract class PrivlegedJavassistAction implements
PrivilegedExceptionAction<String> {
protected Object context;
public void setContext(Object context) {
this.context = context;
}
}
Map<SignatureType, Map<String, List<CommandInterface>>> ExpressionNameToCommand;
/**
* Instantiates a new custom expr editor. from a list of commands. These
* commands are stored in seperate lists to be executed on method calls and
* expressions being translated.
*
* @param editConfigs
* commands to drive the configuration.
*/
public AnnoCustomExprEditor(List<CommandInterface> editConfigs) {
ExpressionNameToCommand = new HashMap<SignatureType, Map<String, List<CommandInterface>>>();
for (CommandInterface curCommand : editConfigs) {
// CommandInterface curCommand = commandIter.next();
Map<String, List<CommandInterface>> sigMap = ExpressionNameToCommand
.get(curCommand.getSignatureType());
if (sigMap == null) {
sigMap = new HashMap<String, List<CommandInterface>>();
ExpressionNameToCommand.put(curCommand.getSignatureType(),
sigMap);
}
List<CommandInterface> commands = sigMap.get(curCommand
.getSignature());
if (commands == null) {
commands = new LinkedList<CommandInterface>();
sigMap.put(curCommand.getSignature(), commands);
}
commands.add(curCommand);
}
}
/**
* this method is for static edits to a class. These happen once and are not
* iterated.
*
* @param clazz
* the clazz to be edited
*/
public synchronized void staticEdits(CtClass clazz) {
Map<String, List<CommandInterface>> sigTypeMap = ExpressionNameToCommand
.get(SignatureType.METHODBODY);
performStaticEdits(clazz, sigTypeMap);
sigTypeMap = ExpressionNameToCommand
.get(SignatureType.STATICDEFINITION);
performStaticEdits(clazz, sigTypeMap);
}
private void performStaticEdits(CtClass clazz,
Map<String, List<CommandInterface>> sigTypeMap) {
if (sigTypeMap != null) {
for (CtMethod method : clazz.getDeclaredMethods()) {
String methodName = method.getLongName();
int nameStart = method.getLongName()
.substring(0, method.getLongName().indexOf('('))
.lastIndexOf('.');
methodName = methodName.substring(nameStart + 1);
List<CommandInterface> listOfCommands = sigTypeMap
.get(methodName);
if (listOfCommands != null) {
for (CommandInterface curCommand : listOfCommands) {
// CommandInterface curCommand = iterCommand.next();
try {
curCommand.translate(method, methodName);
} catch (Exception e) {
logger.error(
"Could not perform Static edit: ["
+ methodName + ","
+ curCommand.getSignature() + "]",
e);
}
}
}
}
}
}
/**
* Conversion of an Expr.
*
* @param ccall
* the expression ccall
* @param commandList
* the list of commands to use to perform the edit.
* @param expressionName
* the name of the expression being edited.
*/
private void convert(Expr ccall, List<CommandInterface> commandList,
boolean isSuper) {
if (commandList != null) {
for (CommandInterface curCommand : commandList) {
try {
curCommand.translate(ccall, isSuper);
} catch (MalformedCommandException e) {
logger.error(
"The command is not written correctly please revise it: "
+ curCommand.toString(), e);
} catch (CannotCompileException e) {
logger.error("Could not compile the replacement text: "
+ curCommand.getReplacement(), e);
}
}
}
else
{
if(ccall instanceof MethodCall)
{
try {
boolean rewrite = true;
MethodCall call = (MethodCall)ccall;
// CtClass[] interfaces = call.getMethod().getDeclaringClass().getInterfaces();
CtClass clazz = call.getMethod().getDeclaringClass();
if(clazz.getName().startsWith("org.annoflow") || clazz.getName().startsWith("javassist") || clazz.getName().startsWith("java"))
{
rewrite = false;
}
// else
// {
// for(CtClass clazz : interfaces)
// {
// if(clazz.getName().startsWith("org.annoflow"))
// {
// rewrite = false;
// break;
// }
// }
// }
if(rewrite)
call.replace("org.annoflow.audit.ContextTracker.getInstance().setCallerContext(\""+ call.getEnclosingClass().getName()+"\");$_=$proceed($$);org.annoflow.audit.ContextTracker.getInstance().clear();");
} catch (CannotCompileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public List<CommandInterface> getCommandList(SignatureType sigType,
String signature) {
Map<String, List<CommandInterface>> callToCommand = ExpressionNameToCommand
.get(sigType);
if (callToCommand != null) {
return callToCommand.get(signature);
}
return null;
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.Handler)
*/
public void edit(Handler ccall) {
/*
* try { PrivlegedJavassistAction action = new
* PrivlegedJavassistAction() {
*
* @Override public String run() throws NotFoundException { CtClass type
* = ((Handler)context).getType(); if(type ==null) { return ""; } return
* type.getName(); }
*
* }; action.setContext(ccall); String constName =
* AccessController.doPrivileged(action);
* logger.trace("Attempting to rewrite "+constName); //String handlerSig
* = ccall.getType().getName(); convert(ccall,
* getCommandList(SignatureType.HANDLER, constName), false); } catch
* (PrivilegedActionException e) {
* logger.error("Exception occured rewriting a Handler call in "
* +ccall.getFileName()); e.printStackTrace(); }
*/
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.Cast)
*/
public void edit(Cast ccall) {
/*
* try { PrivlegedJavassistAction action = new
* PrivlegedJavassistAction() {
*
* @Override public String run() throws NotFoundException { return
* ((Cast)context).getType().getName(); }
*
* }; action.setContext(ccall); String constName =
* AccessController.doPrivileged(action);
* logger.trace("Attempting to rewrite "+constName); convert(ccall,
* getCommandList(SignatureType.CAST, constName), false); } catch
* (PrivilegedActionException e) {
* logger.error("Exception occured rewriting a Cast call in "
* +ccall.getFileName()); e.printStackTrace(); }
*/
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.Instanceof)
*/
public void edit(Instanceof ccall) {
/*
* try { PrivlegedJavassistAction action = new
* PrivlegedJavassistAction() {
*
* @Override public String run() throws NotFoundException { return
* ((Instanceof)context).getType().getName(); }
*
* }; action.setContext(ccall); String constName =
* AccessController.doPrivileged(action);
* logger.trace("Attempting to rewrite "+constName); convert(ccall,
* getCommandList(SignatureType.INSTANCEOF, constName), false); } catch
* (PrivilegedActionException e) {
* logger.error("Exception occured rewriting a Instance of call in "
* +ccall.getFileName()); e.printStackTrace(); }
*/
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.FieldAccess)
*/
public void edit(FieldAccess ccall) {
try {
Object[] annotations = ccall.getField().getAnnotations();
for (Object anno : annotations) {
if (anno instanceof Policy) {
Policy annoPolicy = (Policy) anno;
Class<? extends PolicyType> policyClass = annoPolicy
.policy();
PolicyType policy = policyClass.newInstance();
if (ccall.isWriter()) {
logger.info("Adding policy to write op on field "
+ ccall.getFieldName() + " in class "
+ ccall.getEnclosingClass().getName());
ccall.replace("$_=$proceed($$);org.annoflow.policy.PolicyManager.addFieldPolicy("
+ ccall.getFieldName()
+ ","
+ policy.getClass().getCanonicalName()
+ ".class);");
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (CannotCompileException e) {
e.printStackTrace();
}
// TODO: This probably does not work! If you attempt to access the field
// in a super class this may fall apart.
/*
* try { action.setClass(ccall.getType()); String fieldName =
* ccall.getField().getName(); convert(ccall,
* getCommandList(SignatureType.FIELDACCESS, fieldName), false); } catch
* (NotFoundException e) {
* System.err.println("Could not find class for array type");
* e.printStackTrace(); }
*/
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.NewArray)
*/
public void edit(NewArray ccall) {
/*
* try { PrivlegedJavassistAction action = new
* PrivlegedJavassistAction() {
*
* @Override public String run() throws NotFoundException { return
* ((NewArray)context).getComponentType().getName(); }
*
* }; action.setContext(ccall); String constName =
* AccessController.doPrivileged(action);
* logger.trace("Attempting to rewrite "+constName); convert(ccall,
* getCommandList(SignatureType.NEWARRAY, constName), false); } catch
* (PrivilegedActionException e) {
* logger.error("Exception occured rewriting a NewArray call in "
* +ccall.getFileName()); e.printStackTrace(); }
*/
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.MethodCall)
*/
public void edit(MethodCall ccall) {
try {
PrivlegedJavassistAction action = new PrivlegedJavassistAction() {
@Override
public String run() throws NotFoundException {
return ((MethodCall) context).getMethod().getLongName();
}
};
action.setContext(ccall);
String constName = (String) AccessController.doPrivileged(action);
logger.trace("Attempting to rewrite " + constName);
convert(ccall, getCommandList(SignatureType.METHODCALL, constName),
ccall.isSuper());
} catch (PrivilegedActionException e) {
logger.error("Exception occured rewriting a MethodCall call in "
+ ccall.getFileName(), e);
}
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.ConstructorCall)
*/
public void edit(ConstructorCall ccall) {
try {
PrivlegedJavassistAction action = new PrivlegedJavassistAction() {
@Override
public String run() throws NotFoundException {
return ((ConstructorCall) context).getConstructor()
.getLongName();
}
};
action.setContext(ccall);
String constName = AccessController.doPrivileged(action);
logger.trace("Attempting to rewrite " + constName);
convert(ccall,
getCommandList(SignatureType.CONSTRUCTORCALL, constName),
ccall.isSuper());
} catch (PrivilegedActionException e) {
logger.error(
"Exception occured rewriting a ConstructorCall call in "
+ ccall.getFileName(), e);
}
}
/*
* (non-Javadoc)
*
* @see javassist.expr.ExprEditor#edit(javassist.expr.NewExpr)
*/
public void edit(NewExpr ccall) {
try {
PrivlegedJavassistAction action = new PrivlegedJavassistAction() {
@Override
public String run() throws NotFoundException {
return ((NewExpr) context).getConstructor().getLongName();
}
};
action.setContext(ccall);
String constName = AccessController.doPrivileged(action);
logger.trace("Attempting to rewrite " + constName);
List<CommandInterface> commands = getCommandList(
SignatureType.NEWEXPR, constName);
if (commands != null) {
convert(ccall, commands, false);
} else {
checkPolicy(ccall);
}
} catch (PrivilegedActionException e) {
logger.error("Exception occured rewriting a NewExpr call in "
+ ccall.getFileName(), e);
} catch (CannotCompileException e2) {
logger.error(
"Exception occured when adding the policy check to the new Expression",
e2);
}
}
private void checkPolicy(NewExpr expr) throws CannotCompileException {
expr.replace("$_=$proceed($$);org.annoflow.audit.ContextTracker.getInstance().setCallerContext(\""+expr.getEnclosingClass().getName()+"\");org.annoflow.policy.PolicyManager.addObjectPolicy($_);org.annoflow.audit.ContextTracker.getInstance().clear();");
}
}
| Java |
package cloudspace.vm.javassist;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javassist.ClassPool;
import javassist.CtClass;
/**
* A factory for creating Translator objects. This stores configuration options
* for the creation of a configurable translator.
*/
public class TranslatorProvider
{
/** The eef singleton. */
private static TranslatorProvider eefSingleton = new TranslatorProvider();
/** The translator configs. */
private ConfigParser translatorConfig;
/**
* Instantiates a new translator factory.
*/
private TranslatorProvider()
{
}
/**
* Gets the expr editor factory.
*
* @return the expr editor factory
*/
public static TranslatorProvider getExprEditorFactory()
{
return eefSingleton;
}
/**
* Adds the config file.
*
* @param userFile
* the user file
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public void addConfigFile(File userFile,
ClassPool proxyPool) throws IOException
{
translatorConfig = new ConfigParser(userFile, proxyPool);
}
/**
* Gets a list of configurable translators from the configurations
* registered.
*
* @return the translators
*
* @throws MalformedConfigurationException
* the malformed configuration exception
*/
public List<AnnoTranslator> getTranslators()
throws MalformedConfigurationException
{
List<AnnoTranslator> translators = new ArrayList<AnnoTranslator>();
try
{
translatorConfig.autoUpdate();
}
catch (IOException e)
{
translatorConfig = null;
throw new MalformedConfigurationException("The configuration file has been removed from the system");
}
//Annoflow change
AnnoTranslator configTrans = new AnnoTranslator(translatorConfig);/*new ConfigurableTranslatorLoader(translatorConfig)*/;
translators.add(configTrans);
return translators;
}
public CtClass getProxy(String className)
{
return translatorConfig.getProxy(className);
}
}
| Java |
import org.annoflow.filter.Filter;
import org.annoflow.filter.NetworkFilter;
import dummy.lib.NativeObject;
import dummy.test.perf.ZHTMLTestClass;
public class FilterNetworkTest implements ZHTMLTestClass{
public static void sendObjHook() {
//System.err.println("Getting printed here");
NativeObject nObj = new NativeObject();
try {
sendObj(nObj);
}
catch (Exception ex) {
//Okay
}
}
@Filter(type=NetworkFilter.class)
public static void sendObj(Object obj) {
assert false;
}
@Override
public void loadClasses() {
new NativeObject();
}
@Override
public void doTest() {
sendObj(new NativeObject());
}
}
| Java |
//import org.annoflow.filter.Filter;
//Annotate secure policy here.
public class PrivateDataSink
{
private String password = "foo";
//@Filter(type=SecureBoundary.class)
public String getPassword()
{
return password;
}
}
| Java |
import org.annoflow.filter.Filter;
import org.annoflow.filter.sqli.SQLBoundFilter;
import dummy.test.perf.ZHTMLTestClass;
public class SQLFilterTest implements ZHTMLTestClass {
public static void sendSQL()
{
commitChange("DROP USERS;","foo");
}
@Filter(type=SQLBoundFilter.class)
public static void commitChange(String username, String password)
{
}
@Override
public void loadClasses() {
}
@Override
public void doTest() {
sendSQL();
}
}
| Java |
import org.annoflow.filter.AuditFilter;
import org.annoflow.filter.Filter;
import dummy.test.perf.ZHTMLTestClass;
public class FilterMethodTest implements ZHTMLTestClass
{
public static void filterMe()
{
TSPassword o = new TSPassword("password123");
filterMeBad(o);
assert true;
}
@Filter(type=AuditFilter.class)
public static void filterMeBad(TSPassword o)
{
}
@Override
public void loadClasses() {
new TSPassword("blah");
}
@Override
public void doTest() {
filterMe();
}
}
| Java |
import org.annoflow.filter.Filter;
import org.annoflow.filter.xss.XSSFilter;
import dummy.test.perf.ZHTMLTestClass;
public class XSSFilterTest implements ZHTMLTestClass {
public void loadClasses() {
}
public void doTest() {
try {
printToHTML("<script>alert(\'hello\');</script>");
} catch (Exception ex) {
System.out.println("Successfully blocked XSS attack!");
}
}
@Filter(type = XSSFilter.class)
private static void printToHTML(String html) {
//System.out.println(html);
}
}
| Java |
import org.annoflow.filter.Filter;
import org.annoflow.filter.sqli.SQLBoundFilter;
import org.annoflow.filter.xss.SanitizeHTMLFilter;
import org.annoflow.filter.xss.XSSFilter;
import dummy.lib.UserForm;
import dummy.test.perf.ZHTMLTestClass;
public class UserInputTest implements ZHTMLTestClass {
public void loadClasses() {
}
public void doTest() {
String name = "John"; /* Simulated user input */
String greeting = "Hello, World!"; /* Simulated user input */
int id = 100; /* Simulated system-generated value */
/* Create a form based on the inputs */
UserForm form = new UserForm(id, name, greeting);
// Store to a backend DB
try {
commitToDatabase(id, name, greeting);
} catch (Exception e) {
System.out.println("Caught SQL injection attempt!");
return;
}
// Now display it back to the user
try {
String str = toHTML(form);
System.out.println(str);
} catch (Exception e) {
System.out.println("Caught potentially unsafe printing!");
// Sanitize the HTML and try again
String str = toHTML(sanitize(form));
System.out.println(toHTML(str));
}
}
@Filter(type = SQLBoundFilter.class)
private static void commitToDatabase(int id, String name, String greeting) {
/* Simulated write to database */
}
@Filter(type = XSSFilter.class)
private static String toHTML(Object obj) {
StringBuilder msg = new StringBuilder();
msg.append("<html>");
msg.append(obj.toString());
msg.append("</html>");
return msg.toString();
}
@Filter(type = SanitizeHTMLFilter.class)
private static String sanitize(Object obj) {
return obj.toString();
}
}
| Java |
import org.annoflow.policy.TopSecretPolicy;
import org.annoflow.policy.TopSecret;
import org.annoflow.policy.Policy;
@TopSecret
public class TSPassword
{
@Policy(policy = TopSecretPolicy.class)
private String password;
public TSPassword(String pw)
{
this.password = pw;
}
public String getPassword()
{
return password;
}
public String toString()
{
return password;
}
}
| Java |
import org.annoflow.policy.Policy;
import org.annoflow.policy.UserInputPolicy;
public class UserForm {
private int id;
@Policy(policy=UserInputPolicy.class)
private String name;
@Policy(policy=UserInputPolicy.class)
private String greeting;
public UserForm(int i, String n, String g) {
this.id = i;
this.name = n;
this.greeting = g;
}
public String getName() {
return name;
}
public String getGreeting() {
return greeting;
}
protected int getId() {
return id;
}
public String toString() {
return greeting + " " + name;
}
}
| Java |
import org.annoflow.policy.AnchoredPolicy;
import org.annoflow.policy.Policy;
@Policy(policy=AnchoredPolicy.class)
public class NativeObject {
private int x;
public NativeObject() {
this.x = 0;
}
public NativeObject(int x) {
this.x = x;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
| Java |
/* Copyright 2011 Google Inc.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* Project home page: http://code.google.com/p/usb-serial-for-android/
*/
package com.hoho.android.usbserial.driver;
import java.util.Map;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
/**
* Helper class to assist in detecting and building {@link UsbSerialDriver}
* instances from available hardware.
*
* @author mike wakerly (opensource@hoho.com)
*/
public enum UsbSerialProber {
// TODO(mikey): Too much boilerplate.
/**
* Prober for {@link FtdiSerialDriver}.
*
* @see FtdiSerialDriver
*/
FTDI_SERIAL {
@Override
public UsbSerialDriver getDevice(final UsbManager manager, final UsbDevice usbDevice) {
if (!testIfSupported(usbDevice, FtdiSerialDriver.getSupportedDevices())) {
return null;
}
final UsbDeviceConnection connection = manager.openDevice(usbDevice);
if (connection == null) {
return null;
}
return new FtdiSerialDriver(usbDevice, connection);
}
},
CDC_ACM_SERIAL {
@Override
public UsbSerialDriver getDevice(UsbManager manager, UsbDevice usbDevice) {
if (!testIfSupported(usbDevice, CdcAcmSerialDriver.getSupportedDevices())) {
return null;
}
final UsbDeviceConnection connection = manager.openDevice(usbDevice);
if (connection == null) {
return null;
}
return new CdcAcmSerialDriver(usbDevice, connection);
}
},
SILAB_SERIAL {
@Override
public UsbSerialDriver getDevice(final UsbManager manager, final UsbDevice usbDevice) {
if (!testIfSupported(usbDevice, Cp2102SerialDriver.getSupportedDevices())) {
return null;
}
final UsbDeviceConnection connection = manager.openDevice(usbDevice);
if (connection == null) {
return null;
}
return new Cp2102SerialDriver(usbDevice, connection);
}
};
/**
* Builds a new {@link UsbSerialDriver} instance from the raw device, or
* returns <code>null</code> if it could not be built (for example, if the
* probe failed).
*
* @param manager the {@link UsbManager} to use
* @param usbDevice the raw {@link UsbDevice} to use
* @return the first available {@link UsbSerialDriver}, or {@code null} if
* no devices could be acquired
*/
public abstract UsbSerialDriver getDevice(final UsbManager manager, final UsbDevice usbDevice);
/**
* Acquires and returns the first available serial device among all
* available {@link UsbDevice}s, or returns {@code null} if no device could
* be acquired.
*
* @param usbManager the {@link UsbManager} to use
* @return the first available {@link UsbSerialDriver}, or {@code null} if
* no devices could be acquired
*/
public static UsbSerialDriver acquire(final UsbManager usbManager) {
for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
final UsbSerialDriver probedDevice = acquire(usbManager, usbDevice);
if (probedDevice != null) {
return probedDevice;
}
}
return null;
}
/**
* Builds and returns a new {@link UsbSerialDriver} from the given
* {@link UsbDevice}, or returns {@code null} if no drivers supported this
* device.
*
* @param usbManager the {@link UsbManager} to use
* @param usbDevice the {@link UsbDevice} to use
* @return a new {@link UsbSerialDriver}, or {@code null} if no devices
* could be acquired
*/
public static UsbSerialDriver acquire(final UsbManager usbManager, final UsbDevice usbDevice) {
for (final UsbSerialProber prober : values()) {
final UsbSerialDriver probedDevice = prober.getDevice(usbManager, usbDevice);
if (probedDevice != null) {
return probedDevice;
}
}
return null;
}
/**
* Returns {@code true} if the given device is found in the vendor/product map.
*
* @param usbDevice the device to test
* @param supportedDevices map of vendor ids to product id(s)
* @return {@code true} if supported
*/
private static boolean testIfSupported(final UsbDevice usbDevice,
final Map<Integer, int[]> supportedDevices) {
final int[] supportedProducts = supportedDevices.get(
Integer.valueOf(usbDevice.getVendorId()));
if (supportedProducts == null) {
return false;
}
final int productId = usbDevice.getProductId();
for (int supportedProductId : supportedProducts) {
if (productId == supportedProductId) {
return true;
}
}
return false;
}
}
| Java |
/* Copyright 2011 Google Inc.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* Project home page: http://code.google.com/p/usb-serial-for-android/
*/
package com.hoho.android.usbserial.driver;
import java.io.IOException;
/**
* Driver interface for a USB serial device.
*
* @author mike wakerly (opensource@hoho.com)
*/
public interface UsbSerialDriver {
/** 5 data bits. */
public static final int DATABITS_5 = 5;
/** 6 data bits. */
public static final int DATABITS_6 = 6;
/** 7 data bits. */
public static final int DATABITS_7 = 7;
/** 8 data bits. */
public static final int DATABITS_8 = 8;
/** No flow control. */
public static final int FLOWCONTROL_NONE = 0;
/** RTS/CTS input flow control. */
public static final int FLOWCONTROL_RTSCTS_IN = 1;
/** RTS/CTS output flow control. */
public static final int FLOWCONTROL_RTSCTS_OUT = 2;
/** XON/XOFF input flow control. */
public static final int FLOWCONTROL_XONXOFF_IN = 4;
/** XON/XOFF output flow control. */
public static final int FLOWCONTROL_XONXOFF_OUT = 8;
/** No parity. */
public static final int PARITY_NONE = 0;
/** Odd parity. */
public static final int PARITY_ODD = 1;
/** Even parity. */
public static final int PARITY_EVEN = 2;
/** Mark parity. */
public static final int PARITY_MARK = 3;
/** Space parity. */
public static final int PARITY_SPACE = 4;
/** 1 stop bit. */
public static final int STOPBITS_1 = 1;
/** 1.5 stop bits. */
public static final int STOPBITS_1_5 = 3;
/** 2 stop bits. */
public static final int STOPBITS_2 = 2;
/**
* Opens and initializes the device as a USB serial device. Upon success,
* caller must ensure that {@link #close()} is eventually called.
*
* @throws IOException on error opening or initializing the device.
*/
public void open() throws IOException;
/**
* Closes the serial device.
*
* @throws IOException on error closing the device.
*/
public void close() throws IOException;
/**
* Reads as many bytes as possible into the destination buffer.
*
* @param dest the destination byte buffer
* @param timeoutMillis the timeout for reading
* @return the actual number of bytes read
* @throws IOException if an error occurred during reading
*/
public int read(final byte[] dest, final int timeoutMillis) throws IOException;
/**
* Writes as many bytes as possible from the source buffer.
*
* @param src the source byte buffer
* @param timeoutMillis the timeout for writing
* @return the actual number of bytes written
* @throws IOException if an error occurred during writing
*/
public int write(final byte[] src, final int timeoutMillis) throws IOException;
/**
* Sets various serial port parameters.
*
* @param baudRate baud rate as an integer, for example {@code 115200}.
* @param dataBits one of {@link #DATABITS_5}, {@link #DATABITS_6},
* {@link #DATABITS_7}, or {@link #DATABITS_8}.
* @param stopBits one of {@link #STOPBITS_1}, {@link #STOPBITS_1_5}, or
* {@link #STOPBITS_2}.
* @param parity one of {@link #PARITY_NONE}, {@link #PARITY_ODD},
* {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or
* {@link #PARITY_SPACE}.
* @throws IOException on error setting the port parameters
*/
public void setParameters(
int baudRate, int dataBits, int stopBits, int parity) throws IOException;
/**
* Gets the CD (Carrier Detect) bit from the underlying UART.
*
* @return the current state, or {@code false} if not supported.
* @throws IOException if an error occurred during reading
*/
public boolean getCD() throws IOException;
/**
* Gets the CTS (Clear To Send) bit from the underlying UART.
*
* @return the current state, or {@code false} if not supported.
* @throws IOException if an error occurred during reading
*/
public boolean getCTS() throws IOException;
/**
* Gets the DSR (Data Set Ready) bit from the underlying UART.
*
* @return the current state, or {@code false} if not supported.
* @throws IOException if an error occurred during reading
*/
public boolean getDSR() throws IOException;
/**
* Gets the DTR (Data Terminal Ready) bit from the underlying UART.
*
* @return the current state, or {@code false} if not supported.
* @throws IOException if an error occurred during reading
*/
public boolean getDTR() throws IOException;
/**
* Sets the DTR (Data Terminal Ready) bit on the underlying UART, if
* supported.
*
* @param value the value to set
* @throws IOException if an error occurred during writing
*/
public void setDTR(boolean value) throws IOException;
/**
* Gets the RI (Ring Indicator) bit from the underlying UART.
*
* @return the current state, or {@code false} if not supported.
* @throws IOException if an error occurred during reading
*/
public boolean getRI() throws IOException;
/**
* Gets the RTS (Request To Send) bit from the underlying UART.
*
* @return the current state, or {@code false} if not supported.
* @throws IOException if an error occurred during reading
*/
public boolean getRTS() throws IOException;
/**
* Sets the RTS (Request To Send) bit on the underlying UART, if
* supported.
*
* @param value the value to set
* @throws IOException if an error occurred during writing
*/
public void setRTS(boolean value) throws IOException;
}
| Java |
package com.hoho.android.usbserial.driver;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.util.Log;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* USB CDC/ACM serial driver implementation.
*
* @author mike wakerly (opensource@hoho.com)
* @see <a
* href="http://www.usb.org/developers/devclass_docs/usbcdc11.pdf">Universal
* Serial Bus Class Definitions for Communication Devices, v1.1</a>
*/
public class CdcAcmSerialDriver extends CommonUsbSerialDriver {
private final String TAG = CdcAcmSerialDriver.class.getSimpleName();
private UsbInterface mControlInterface;
private UsbInterface mDataInterface;
private UsbEndpoint mControlEndpoint;
private UsbEndpoint mReadEndpoint;
private UsbEndpoint mWriteEndpoint;
private boolean mRts = false;
private boolean mDtr = false;
private static final int USB_RECIP_INTERFACE = 0x01;
private static final int USB_RT_ACM = UsbConstants.USB_TYPE_CLASS | USB_RECIP_INTERFACE;
private static final int SET_LINE_CODING = 0x20; // USB CDC 1.1 section 6.2
private static final int GET_LINE_CODING = 0x21;
private static final int SET_CONTROL_LINE_STATE = 0x22;
private static final int SEND_BREAK = 0x23;
public CdcAcmSerialDriver(UsbDevice device, UsbDeviceConnection connection) {
super(device, connection);
}
@Override
public void open() throws IOException {
Log.d(TAG, "claiming interfaces, count=" + mDevice.getInterfaceCount());
Log.d(TAG, "Claiming control interface.");
mControlInterface = mDevice.getInterface(0);
Log.d(TAG, "Control iface=" + mControlInterface);
// class should be USB_CLASS_COMM
if (!mConnection.claimInterface(mControlInterface, true)) {
throw new IOException("Could not claim control interface.");
}
mControlEndpoint = mControlInterface.getEndpoint(0);
Log.d(TAG, "Control endpoint direction: " + mControlEndpoint.getDirection());
Log.d(TAG, "Claiming data interface.");
mDataInterface = mDevice.getInterface(1);
Log.d(TAG, "data iface=" + mDataInterface);
// class should be USB_CLASS_CDC_DATA
if (!mConnection.claimInterface(mDataInterface, true)) {
throw new IOException("Could not claim data interface.");
}
mReadEndpoint = mDataInterface.getEndpoint(1);
Log.d(TAG, "Read endpoint direction: " + mReadEndpoint.getDirection());
mWriteEndpoint = mDataInterface.getEndpoint(0);
Log.d(TAG, "Write endpoint direction: " + mWriteEndpoint.getDirection());
}
private int sendAcmControlMessage(int request, int value, byte[] buf) {
return mConnection.controlTransfer(
USB_RT_ACM, request, value, 0, buf, buf != null ? buf.length : 0, 5000);
}
@Override
public void close() throws IOException {
mConnection.close();
}
@Override
public int read(byte[] dest, int timeoutMillis) throws IOException {
final int numBytesRead;
synchronized (mReadBufferLock) {
int readAmt = Math.min(dest.length, mReadBuffer.length);
numBytesRead = mConnection.bulkTransfer(mReadEndpoint, mReadBuffer, readAmt,
timeoutMillis);
if (numBytesRead < 0) {
// This sucks: we get -1 on timeout, not 0 as preferred.
// We *should* use UsbRequest, except it has a bug/api oversight
// where there is no way to determine the number of bytes read
// in response :\ -- http://b.android.com/28023
return 0;
}
System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead);
}
return numBytesRead;
}
@Override
public int write(byte[] src, int timeoutMillis) throws IOException {
// TODO(mikey): Nearly identical to FtdiSerial write. Refactor.
int offset = 0;
while (offset < src.length) {
final int writeLength;
final int amtWritten;
synchronized (mWriteBufferLock) {
final byte[] writeBuffer;
writeLength = Math.min(src.length - offset, mWriteBuffer.length);
if (offset == 0) {
writeBuffer = src;
} else {
// bulkTransfer does not support offsets, make a copy.
System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
writeBuffer = mWriteBuffer;
}
amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength,
timeoutMillis);
}
if (amtWritten <= 0) {
throw new IOException("Error writing " + writeLength
+ " bytes at offset " + offset + " length=" + src.length);
}
Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength);
offset += amtWritten;
}
return offset;
}
@Override
public void setParameters(int baudRate, int dataBits, int stopBits, int parity) {
byte stopBitsByte;
switch (stopBits) {
case STOPBITS_1: stopBitsByte = 0; break;
case STOPBITS_1_5: stopBitsByte = 1; break;
case STOPBITS_2: stopBitsByte = 2; break;
default: throw new IllegalArgumentException("Bad value for stopBits: " + stopBits);
}
byte parityBitesByte;
switch (parity) {
case PARITY_NONE: parityBitesByte = 0; break;
case PARITY_ODD: parityBitesByte = 1; break;
case PARITY_EVEN: parityBitesByte = 2; break;
case PARITY_MARK: parityBitesByte = 3; break;
case PARITY_SPACE: parityBitesByte = 4; break;
default: throw new IllegalArgumentException("Bad value for parity: " + parity);
}
byte[] msg = {
(byte) ( baudRate & 0xff),
(byte) ((baudRate >> 8 ) & 0xff),
(byte) ((baudRate >> 16) & 0xff),
(byte) ((baudRate >> 24) & 0xff),
stopBitsByte,
parityBitesByte,
(byte) dataBits};
sendAcmControlMessage(SET_LINE_CODING, 0, msg);
}
@Override
public boolean getCD() throws IOException {
return false; // TODO
}
@Override
public boolean getCTS() throws IOException {
return false; // TODO
}
@Override
public boolean getDSR() throws IOException {
return false; // TODO
}
@Override
public boolean getDTR() throws IOException {
return mDtr;
}
@Override
public void setDTR(boolean value) throws IOException {
mDtr = value;
setDtrRts();
}
@Override
public boolean getRI() throws IOException {
return false; // TODO
}
@Override
public boolean getRTS() throws IOException {
return mRts;
}
@Override
public void setRTS(boolean value) throws IOException {
mRts = value;
setDtrRts();
}
private void setDtrRts() {
int value = (mRts ? 0x2 : 0) | (mDtr ? 0x1 : 0);
sendAcmControlMessage(SET_CONTROL_LINE_STATE, value, null);
}
public static Map<Integer, int[]> getSupportedDevices() {
final Map<Integer, int[]> supportedDevices = new LinkedHashMap<Integer, int[]>();
supportedDevices.put(Integer.valueOf(UsbId.VENDOR_ARDUINO),
new int[] {
UsbId.ARDUINO_UNO,
UsbId.ARDUINO_UNO_R3,
UsbId.ARDUINO_MEGA_2560,
UsbId.ARDUINO_MEGA_2560_R3,
UsbId.ARDUINO_SERIAL_ADAPTER,
UsbId.ARDUINO_SERIAL_ADAPTER_R3,
UsbId.ARDUINO_MEGA_ADK,
UsbId.ARDUINO_MEGA_ADK_R3,
UsbId.ARDUINO_LEONARDO,
});
supportedDevices.put(Integer.valueOf(UsbId.VENDOR_VAN_OOIJEN_TECH),
new int[] {
UsbId.VAN_OOIJEN_TECH_TEENSYDUINO_SERIAL,
});
supportedDevices.put(Integer.valueOf(UsbId.VENDOR_ATMEL),
new int[] {
UsbId.ATMEL_LUFA_CDC_DEMO_APP,
});
supportedDevices.put(Integer.valueOf(UsbId.VENDOR_LEAFLABS),
new int[] {
UsbId.LEAFLABS_MAPLE,
});
return supportedDevices;
}
}
| Java |
/* Copyright 2013 Google Inc.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* Project home page: http://code.google.com/p/usb-serial-for-android/
*/
package com.hoho.android.usbserial.driver;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import java.io.IOException;
/**
* A base class shared by several driver implementations.
*
* @author mike wakerly (opensource@hoho.com)
*/
abstract class CommonUsbSerialDriver implements UsbSerialDriver {
public static final int DEFAULT_READ_BUFFER_SIZE = 16 * 1024;
public static final int DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
protected final UsbDevice mDevice;
protected final UsbDeviceConnection mConnection;
protected final Object mReadBufferLock = new Object();
protected final Object mWriteBufferLock = new Object();
/** Internal read buffer. Guarded by {@link #mReadBufferLock}. */
protected byte[] mReadBuffer;
/** Internal write buffer. Guarded by {@link #mWriteBufferLock}. */
protected byte[] mWriteBuffer;
public CommonUsbSerialDriver(UsbDevice device, UsbDeviceConnection connection) {
mDevice = device;
mConnection = connection;
mReadBuffer = new byte[DEFAULT_READ_BUFFER_SIZE];
mWriteBuffer = new byte[DEFAULT_WRITE_BUFFER_SIZE];
}
/**
* Returns the currently-bound USB device.
*
* @return the device
*/
public final UsbDevice getDevice() {
return mDevice;
}
/**
* Sets the size of the internal buffer used to exchange data with the USB
* stack for read operations. Most users should not need to change this.
*
* @param bufferSize the size in bytes
*/
public final void setReadBufferSize(int bufferSize) {
synchronized (mReadBufferLock) {
if (bufferSize == mReadBuffer.length) {
return;
}
mReadBuffer = new byte[bufferSize];
}
}
/**
* Sets the size of the internal buffer used to exchange data with the USB
* stack for write operations. Most users should not need to change this.
*
* @param bufferSize the size in bytes
*/
public final void setWriteBufferSize(int bufferSize) {
synchronized (mWriteBufferLock) {
if (bufferSize == mWriteBuffer.length) {
return;
}
mWriteBuffer = new byte[bufferSize];
}
}
@Override
public abstract void open() throws IOException;
@Override
public abstract void close() throws IOException;
@Override
public abstract int read(final byte[] dest, final int timeoutMillis) throws IOException;
@Override
public abstract int write(final byte[] src, final int timeoutMillis) throws IOException;
@Override
public abstract void setParameters(
int baudRate, int dataBits, int stopBits, int parity) throws IOException;
@Override
public abstract boolean getCD() throws IOException;
@Override
public abstract boolean getCTS() throws IOException;
@Override
public abstract boolean getDSR() throws IOException;
@Override
public abstract boolean getDTR() throws IOException;
@Override
public abstract void setDTR(boolean value) throws IOException;
@Override
public abstract boolean getRI() throws IOException;
@Override
public abstract boolean getRTS() throws IOException;
@Override
public abstract void setRTS(boolean value) throws IOException;
}
| Java |
/* Copyright 2012 Google Inc.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* Project home page: http://code.google.com/p/usb-serial-for-android/
*/
package com.hoho.android.usbserial.driver;
/**
* Registry of USB vendor/product ID constants.
*
* Culled from various sources; see
* <a href="http://www.linux-usb.org/usb.ids">usb.ids</a> for one listing.
*
* @author mike wakerly (opensource@hoho.com)
*/
public final class UsbId {
public static final int VENDOR_FTDI = 0x0403;
public static final int FTDI_FT232R = 0x6001;
public static final int VENDOR_ATMEL = 0x03EB;
public static final int ATMEL_LUFA_CDC_DEMO_APP = 0x2044;
public static final int VENDOR_ARDUINO = 0x2341;
public static final int ARDUINO_UNO = 0x0001;
public static final int ARDUINO_MEGA_2560 = 0x0010;
public static final int ARDUINO_SERIAL_ADAPTER = 0x003b;
public static final int ARDUINO_MEGA_ADK = 0x003f;
public static final int ARDUINO_MEGA_2560_R3 = 0x0042;
public static final int ARDUINO_UNO_R3 = 0x0043;
public static final int ARDUINO_MEGA_ADK_R3 = 0x0044;
public static final int ARDUINO_SERIAL_ADAPTER_R3 = 0x0044;
public static final int ARDUINO_LEONARDO = 0x8036;
public static final int VENDOR_VAN_OOIJEN_TECH = 0x16c0;
public static final int VAN_OOIJEN_TECH_TEENSYDUINO_SERIAL = 0x0483;
public static final int VENDOR_LEAFLABS = 0x1eaf;
public static final int LEAFLABS_MAPLE = 0x0004;
public static final int VENDOR_SILAB = 0x10c4;
public static final int SILAB_CP2102 = 0xea60;
private UsbId() {
throw new IllegalAccessError("Non-instantiable class.");
}
}
| Java |
package com.hoho.android.usbserial.driver;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.util.Log;
public class Cp2102SerialDriver extends CommonUsbSerialDriver {
private static final String TAG = Cp2102SerialDriver.class.getSimpleName();
private static final int DEFAULT_BAUD_RATE = 9600;
private static final int USB_WRITE_TIMEOUT_MILLIS = 5000;
/*
* Configuration Request Types
*/
private static final int REQTYPE_HOST_TO_DEVICE = 0x41;
/*
* Configuration Request Codes
*/
private static final int SILABSER_IFC_ENABLE_REQUEST_CODE = 0x00;
private static final int SILABSER_SET_BAUDDIV_REQUEST_CODE = 0x01;
private static final int SILABSER_SET_LINE_CTL_REQUEST_CODE = 0x03;
private static final int SILABSER_SET_MHS_REQUEST_CODE = 0x07;
private static final int SILABSER_SET_BAUDRATE = 0x1E;
/*
* SILABSER_IFC_ENABLE_REQUEST_CODE
*/
private static final int UART_ENABLE = 0x0001;
private static final int UART_DISABLE = 0x0000;
/*
* SILABSER_SET_BAUDDIV_REQUEST_CODE
*/
private static final int BAUD_RATE_GEN_FREQ = 0x384000;
/*
* SILABSER_SET_MHS_REQUEST_CODE
*/
private static final int MCR_DTR = 0x0001;
private static final int MCR_RTS = 0x0002;
private static final int MCR_ALL = 0x0003;
private static final int CONTROL_WRITE_DTR = 0x0100;
private static final int CONTROL_WRITE_RTS = 0x0200;
private UsbEndpoint mReadEndpoint;
private UsbEndpoint mWriteEndpoint;
public Cp2102SerialDriver(UsbDevice device, UsbDeviceConnection connection) {
super(device, connection);
}
private int setConfigSingle(int request, int value) {
return mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request, value,
0, null, 0, USB_WRITE_TIMEOUT_MILLIS);
}
@Override
public void open() throws IOException {
boolean opened = false;
try {
for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
UsbInterface usbIface = mDevice.getInterface(i);
if (mConnection.claimInterface(usbIface, true)) {
Log.d(TAG, "claimInterface " + i + " SUCCESS");
} else {
Log.d(TAG, "claimInterface " + i + " FAIL");
}
}
UsbInterface dataIface = mDevice.getInterface(mDevice.getInterfaceCount() - 1);
for (int i = 0; i < dataIface.getEndpointCount(); i++) {
UsbEndpoint ep = dataIface.getEndpoint(i);
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
mReadEndpoint = ep;
} else {
mWriteEndpoint = ep;
}
}
}
setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_ENABLE);
setConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, MCR_ALL | CONTROL_WRITE_DTR | CONTROL_WRITE_RTS);
setConfigSingle(SILABSER_SET_BAUDDIV_REQUEST_CODE, BAUD_RATE_GEN_FREQ / DEFAULT_BAUD_RATE);
// setParameters(DEFAULT_BAUD_RATE, DEFAULT_DATA_BITS, DEFAULT_STOP_BITS, DEFAULT_PARITY);
opened = true;
} finally {
if (!opened) {
close();
}
}
}
@Override
public void close() throws IOException {
setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_DISABLE);
mConnection.close();
}
@Override
public int read(byte[] dest, int timeoutMillis) throws IOException {
final int numBytesRead;
synchronized (mReadBufferLock) {
int readAmt = Math.min(dest.length, mReadBuffer.length);
numBytesRead = mConnection.bulkTransfer(mReadEndpoint, mReadBuffer, readAmt,
timeoutMillis);
if (numBytesRead < 0) {
// This sucks: we get -1 on timeout, not 0 as preferred.
// We *should* use UsbRequest, except it has a bug/api oversight
// where there is no way to determine the number of bytes read
// in response :\ -- http://b.android.com/28023
return 0;
}
System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead);
}
return numBytesRead;
}
@Override
public int write(byte[] src, int timeoutMillis) throws IOException {
int offset = 0;
while (offset < src.length) {
final int writeLength;
final int amtWritten;
synchronized (mWriteBufferLock) {
final byte[] writeBuffer;
writeLength = Math.min(src.length - offset, mWriteBuffer.length);
if (offset == 0) {
writeBuffer = src;
} else {
// bulkTransfer does not support offsets, make a copy.
System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
writeBuffer = mWriteBuffer;
}
amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength,
timeoutMillis);
}
if (amtWritten <= 0) {
throw new IOException("Error writing " + writeLength
+ " bytes at offset " + offset + " length=" + src.length);
}
Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength);
offset += amtWritten;
}
return offset;
}
private void setBaudRate(int baudRate) throws IOException {
byte[] data = new byte[] {
(byte) ( baudRate & 0xff),
(byte) ((baudRate >> 8 ) & 0xff),
(byte) ((baudRate >> 16) & 0xff),
(byte) ((baudRate >> 24) & 0xff)
};
int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_BAUDRATE,
0, 0, data, 4, USB_WRITE_TIMEOUT_MILLIS);
if (ret < 0) {
throw new IOException("Error setting baud rate.");
}
}
@Override
public void setParameters(int baudRate, int dataBits, int stopBits, int parity)
throws IOException {
setBaudRate(baudRate);
int configDataBits = 0;
switch (dataBits) {
case DATABITS_5:
configDataBits |= 0x0500;
break;
case DATABITS_6:
configDataBits |= 0x0600;
break;
case DATABITS_7:
configDataBits |= 0x0700;
break;
case DATABITS_8:
configDataBits |= 0x0800;
break;
default:
configDataBits |= 0x0800;
break;
}
setConfigSingle(SILABSER_SET_LINE_CTL_REQUEST_CODE, configDataBits);
int configParityBits = 0; // PARITY_NONE
switch (parity) {
case PARITY_ODD:
configParityBits |= 0x0010;
break;
case PARITY_EVEN:
configParityBits |= 0x0020;
break;
}
setConfigSingle(SILABSER_SET_LINE_CTL_REQUEST_CODE, configParityBits);
int configStopBits = 0;
switch (stopBits) {
case STOPBITS_1:
configStopBits |= 0;
break;
case STOPBITS_2:
configStopBits |= 2;
break;
}
setConfigSingle(SILABSER_SET_LINE_CTL_REQUEST_CODE, configStopBits);
}
@Override
public boolean getCD() throws IOException {
return false;
}
@Override
public boolean getCTS() throws IOException {
return false;
}
@Override
public boolean getDSR() throws IOException {
return false;
}
@Override
public boolean getDTR() throws IOException {
return true;
}
@Override
public void setDTR(boolean value) throws IOException {
}
@Override
public boolean getRI() throws IOException {
return false;
}
@Override
public boolean getRTS() throws IOException {
return true;
}
@Override
public void setRTS(boolean value) throws IOException {
}
public static Map<Integer, int[]> getSupportedDevices() {
final Map<Integer, int[]> supportedDevices = new LinkedHashMap<Integer, int[]>();
supportedDevices.put(Integer.valueOf(UsbId.VENDOR_SILAB),
new int[] {
UsbId.SILAB_CP2102
});
return supportedDevices;
}
}
| Java |
/* Copyright 2011 Google Inc.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* Project home page: http://code.google.com/p/usb-serial-for-android/
*/
package com.hoho.android.usbserial.driver;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbRequest;
import android.util.Log;
import com.hoho.android.usbserial.util.HexDump;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A {@link CommonUsbSerialDriver} implementation for a variety of FTDI devices
* <p>
* This driver is based on
* <a href="http://www.intra2net.com/en/developer/libftdi">libftdi</a>, and is
* copyright and subject to the following terms:
*
* <pre>
* Copyright (C) 2003 by Intra2net AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation;
*
* opensource@intra2net.com
* http://www.intra2net.com/en/developer/libftdi
* </pre>
*
* </p>
* <p>
* Some FTDI devices have not been tested; see later listing of supported and
* unsupported devices. Devices listed as "supported" support the following
* features:
* <ul>
* <li>Read and write of serial data (see {@link #read(byte[], int)} and
* {@link #write(byte[], int)}.
* <li>Setting baud rate (see {@link #setBaudRate(int)}).
* </ul>
* </p>
* <p>
* Supported and tested devices:
* <ul>
* <li>{@value DeviceType#TYPE_R}</li>
* </ul>
* </p>
* <p>
* Unsupported but possibly working devices (please contact the author with
* feedback or patches):
* <ul>
* <li>{@value DeviceType#TYPE_2232C}</li>
* <li>{@value DeviceType#TYPE_2232H}</li>
* <li>{@value DeviceType#TYPE_4232H}</li>
* <li>{@value DeviceType#TYPE_AM}</li>
* <li>{@value DeviceType#TYPE_BM}</li>
* </ul>
* </p>
*
* @author mike wakerly (opensource@hoho.com)
* @see <a href="http://code.google.com/p/usb-serial-for-android/">USB Serial
* for Android project page</a>
* @see <a href="http://www.ftdichip.com/">FTDI Homepage</a>
* @see <a href="http://www.intra2net.com/en/developer/libftdi">libftdi</a>
*/
public class FtdiSerialDriver extends CommonUsbSerialDriver {
public static final int USB_TYPE_STANDARD = 0x00 << 5;
public static final int USB_TYPE_CLASS = 0x00 << 5;
public static final int USB_TYPE_VENDOR = 0x00 << 5;
public static final int USB_TYPE_RESERVED = 0x00 << 5;
public static final int USB_RECIP_DEVICE = 0x00;
public static final int USB_RECIP_INTERFACE = 0x01;
public static final int USB_RECIP_ENDPOINT = 0x02;
public static final int USB_RECIP_OTHER = 0x03;
public static final int USB_ENDPOINT_IN = 0x80;
public static final int USB_ENDPOINT_OUT = 0x00;
public static final int USB_WRITE_TIMEOUT_MILLIS = 5000;
public static final int USB_READ_TIMEOUT_MILLIS = 5000;
// From ftdi.h
/**
* Reset the port.
*/
private static final int SIO_RESET_REQUEST = 0;
/**
* Set the modem control register.
*/
private static final int SIO_MODEM_CTRL_REQUEST = 1;
/**
* Set flow control register.
*/
private static final int SIO_SET_FLOW_CTRL_REQUEST = 2;
/**
* Set baud rate.
*/
private static final int SIO_SET_BAUD_RATE_REQUEST = 3;
/**
* Set the data characteristics of the port.
*/
private static final int SIO_SET_DATA_REQUEST = 4;
private static final int SIO_RESET_SIO = 0;
public static final int FTDI_DEVICE_OUT_REQTYPE =
UsbConstants.USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT;
public static final int FTDI_DEVICE_IN_REQTYPE =
UsbConstants.USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
/**
* Length of the modem status header, transmitted with every read.
*/
private static final int MODEM_STATUS_HEADER_LENGTH = 2;
private final String TAG = FtdiSerialDriver.class.getSimpleName();
private DeviceType mType;
/**
* FTDI chip types.
*/
private static enum DeviceType {
TYPE_BM, TYPE_AM, TYPE_2232C, TYPE_R, TYPE_2232H, TYPE_4232H;
}
private int mInterface = 0; /* INTERFACE_ANY */
private int mMaxPacketSize = 64; // TODO(mikey): detect
/**
* Due to http://b.android.com/28023 , we cannot use UsbRequest async reads
* since it gives no indication of number of bytes read. Set this to
* {@code true} on platforms where it is fixed.
*/
private static final boolean ENABLE_ASYNC_READS = false;
/**
* Constructor.
*
* @param usbDevice the {@link UsbDevice} to use
* @param usbConnection the {@link UsbDeviceConnection} to use
* @throws UsbSerialRuntimeException if the given device is incompatible
* with this driver
*/
public FtdiSerialDriver(UsbDevice usbDevice, UsbDeviceConnection usbConnection) {
super(usbDevice, usbConnection);
mType = null;
}
public void reset() throws IOException {
int result = mConnection.controlTransfer(FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
SIO_RESET_SIO, 0 /* index */, null, 0, USB_WRITE_TIMEOUT_MILLIS);
if (result != 0) {
throw new IOException("Reset failed: result=" + result);
}
// TODO(mikey): autodetect.
mType = DeviceType.TYPE_R;
}
@Override
public void open() throws IOException {
boolean opened = false;
try {
for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
if (mConnection.claimInterface(mDevice.getInterface(i), true)) {
Log.d(TAG, "claimInterface " + i + " SUCCESS");
} else {
throw new IOException("Error claiming interface " + i);
}
}
reset();
opened = true;
} finally {
if (!opened) {
close();
}
}
}
@Override
public void close() {
mConnection.close();
}
@Override
public int read(byte[] dest, int timeoutMillis) throws IOException {
final UsbEndpoint endpoint = mDevice.getInterface(0).getEndpoint(0);
if (ENABLE_ASYNC_READS) {
final int readAmt;
synchronized (mReadBufferLock) {
// mReadBuffer is only used for maximum read size.
readAmt = Math.min(dest.length, mReadBuffer.length);
}
final UsbRequest request = new UsbRequest();
request.initialize(mConnection, endpoint);
final ByteBuffer buf = ByteBuffer.wrap(dest);
if (!request.queue(buf, readAmt)) {
throw new IOException("Error queueing request.");
}
final UsbRequest response = mConnection.requestWait();
if (response == null) {
throw new IOException("Null response");
}
final int payloadBytesRead = buf.position() - MODEM_STATUS_HEADER_LENGTH;
if (payloadBytesRead > 0) {
Log.d(TAG, HexDump.dumpHexString(dest, 0, Math.min(32, dest.length)));
return payloadBytesRead;
} else {
return 0;
}
} else {
final int totalBytesRead;
synchronized (mReadBufferLock) {
final int readAmt = Math.min(dest.length, mReadBuffer.length);
totalBytesRead = mConnection.bulkTransfer(endpoint, mReadBuffer,
readAmt, timeoutMillis);
}
if (totalBytesRead < MODEM_STATUS_HEADER_LENGTH) {
throw new IOException("Expected at least " + MODEM_STATUS_HEADER_LENGTH + " bytes");
}
final int payloadBytesRead = totalBytesRead - MODEM_STATUS_HEADER_LENGTH;
if (payloadBytesRead > 0) {
System.arraycopy(mReadBuffer, MODEM_STATUS_HEADER_LENGTH, dest, 0, payloadBytesRead);
}
return payloadBytesRead;
}
}
@Override
public int write(byte[] src, int timeoutMillis) throws IOException {
final UsbEndpoint endpoint = mDevice.getInterface(0).getEndpoint(1);
int offset = 0;
while (offset < src.length) {
final int writeLength;
final int amtWritten;
synchronized (mWriteBufferLock) {
final byte[] writeBuffer;
writeLength = Math.min(src.length - offset, mWriteBuffer.length);
if (offset == 0) {
writeBuffer = src;
} else {
// bulkTransfer does not support offsets, make a copy.
System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
writeBuffer = mWriteBuffer;
}
amtWritten = mConnection.bulkTransfer(endpoint, writeBuffer, writeLength,
timeoutMillis);
}
if (amtWritten <= 0) {
throw new IOException("Error writing " + writeLength
+ " bytes at offset " + offset + " length=" + src.length);
}
Log.d(TAG, "Wrote amtWritten=" + amtWritten + " attempted=" + writeLength);
offset += amtWritten;
}
return offset;
}
private int setBaudRate(int baudRate) throws IOException {
long[] vals = convertBaudrate(baudRate);
long actualBaudrate = vals[0];
long index = vals[1];
long value = vals[2];
int result = mConnection.controlTransfer(FTDI_DEVICE_OUT_REQTYPE,
SIO_SET_BAUD_RATE_REQUEST, (int) value, (int) index,
null, 0, USB_WRITE_TIMEOUT_MILLIS);
if (result != 0) {
throw new IOException("Setting baudrate failed: result=" + result);
}
return (int) actualBaudrate;
}
@Override
public void setParameters(int baudRate, int dataBits, int stopBits, int parity)
throws IOException {
setBaudRate(baudRate);
int config = dataBits;
switch (parity) {
case PARITY_NONE:
config |= (0x00 << 8);
break;
case PARITY_ODD:
config |= (0x01 << 8);
break;
case PARITY_EVEN:
config |= (0x02 << 8);
break;
case PARITY_MARK:
config |= (0x03 << 8);
break;
case PARITY_SPACE:
config |= (0x04 << 8);
break;
default:
throw new IllegalArgumentException("Unknown parity value: " + parity);
}
switch (stopBits) {
case STOPBITS_1:
config |= (0x00 << 11);
break;
case STOPBITS_1_5:
config |= (0x01 << 11);
break;
case STOPBITS_2:
config |= (0x02 << 11);
break;
default:
throw new IllegalArgumentException("Unknown stopBits value: " + stopBits);
}
int result = mConnection.controlTransfer(FTDI_DEVICE_OUT_REQTYPE,
SIO_SET_DATA_REQUEST, config, 0 /* index */,
null, 0, USB_WRITE_TIMEOUT_MILLIS);
if (result != 0) {
throw new IOException("Setting parameters failed: result=" + result);
}
}
private long[] convertBaudrate(int baudrate) {
// TODO(mikey): Braindead transcription of libfti method. Clean up,
// using more idiomatic Java where possible.
int divisor = 24000000 / baudrate;
int bestDivisor = 0;
int bestBaud = 0;
int bestBaudDiff = 0;
int fracCode[] = {
0, 3, 2, 4, 1, 5, 6, 7
};
for (int i = 0; i < 2; i++) {
int tryDivisor = divisor + i;
int baudEstimate;
int baudDiff;
if (tryDivisor <= 8) {
// Round up to minimum supported divisor
tryDivisor = 8;
} else if (mType != DeviceType.TYPE_AM && tryDivisor < 12) {
// BM doesn't support divisors 9 through 11 inclusive
tryDivisor = 12;
} else if (divisor < 16) {
// AM doesn't support divisors 9 through 15 inclusive
tryDivisor = 16;
} else {
if (mType == DeviceType.TYPE_AM) {
// TODO
} else {
if (tryDivisor > 0x1FFFF) {
// Round down to maximum supported divisor value (for
// BM)
tryDivisor = 0x1FFFF;
}
}
}
// Get estimated baud rate (to nearest integer)
baudEstimate = (24000000 + (tryDivisor / 2)) / tryDivisor;
// Get absolute difference from requested baud rate
if (baudEstimate < baudrate) {
baudDiff = baudrate - baudEstimate;
} else {
baudDiff = baudEstimate - baudrate;
}
if (i == 0 || baudDiff < bestBaudDiff) {
// Closest to requested baud rate so far
bestDivisor = tryDivisor;
bestBaud = baudEstimate;
bestBaudDiff = baudDiff;
if (baudDiff == 0) {
// Spot on! No point trying
break;
}
}
}
// Encode the best divisor value
long encodedDivisor = (bestDivisor >> 3) | (fracCode[bestDivisor & 7] << 14);
// Deal with special cases for encoded value
if (encodedDivisor == 1) {
encodedDivisor = 0; // 3000000 baud
} else if (encodedDivisor == 0x4001) {
encodedDivisor = 1; // 2000000 baud (BM only)
}
// Split into "value" and "index" values
long value = encodedDivisor & 0xFFFF;
long index;
if (mType == DeviceType.TYPE_2232C || mType == DeviceType.TYPE_2232H
|| mType == DeviceType.TYPE_4232H) {
index = (encodedDivisor >> 8) & 0xffff;
index &= 0xFF00;
index |= 0 /* TODO mIndex */;
} else {
index = (encodedDivisor >> 16) & 0xffff;
}
// Return the nearest baud rate
return new long[] {
bestBaud, index, value
};
}
@Override
public boolean getCD() throws IOException {
return false;
}
@Override
public boolean getCTS() throws IOException {
return false;
}
@Override
public boolean getDSR() throws IOException {
return false;
}
@Override
public boolean getDTR() throws IOException {
return false;
}
@Override
public void setDTR(boolean value) throws IOException {
}
@Override
public boolean getRI() throws IOException {
return false;
}
@Override
public boolean getRTS() throws IOException {
return false;
}
@Override
public void setRTS(boolean value) throws IOException {
}
public static Map<Integer, int[]> getSupportedDevices() {
final Map<Integer, int[]> supportedDevices = new LinkedHashMap<Integer, int[]>();
supportedDevices.put(Integer.valueOf(UsbId.VENDOR_FTDI),
new int[] {
UsbId.FTDI_FT232R,
});
return supportedDevices;
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
package com.hoho.android.usbserial.driver;
/**
* Generic unchecked exception for the usbserial package.
*
* @author mike wakerly (opensource@hoho.com)
*/
@SuppressWarnings("serial")
public class UsbSerialRuntimeException extends RuntimeException {
public UsbSerialRuntimeException() {
super();
}
public UsbSerialRuntimeException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public UsbSerialRuntimeException(String detailMessage) {
super(detailMessage);
}
public UsbSerialRuntimeException(Throwable throwable) {
super(throwable);
}
}
| Java |
/* Copyright 2011 Google Inc.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* Project home page: http://code.google.com/p/usb-serial-for-android/
*/
package com.hoho.android.usbserial.util;
import android.hardware.usb.UsbRequest;
import android.util.Log;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Utility class which services a {@link UsbSerialDriver} in its {@link #run()}
* method.
*
* @author mike wakerly (opensource@hoho.com)
*/
public class SerialInputOutputManager implements Runnable {
private static final String TAG = SerialInputOutputManager.class.getSimpleName();
private static final boolean DEBUG = true;
private static final int READ_WAIT_MILLIS = 200;
private static final int BUFSIZ = 4096;
private final UsbSerialDriver mDriver;
private final ByteBuffer mReadBuffer = ByteBuffer.allocate(BUFSIZ);
// Synchronized by 'mWriteBuffer'
private final ByteBuffer mWriteBuffer = ByteBuffer.allocate(BUFSIZ);
private enum State {
STOPPED,
RUNNING,
STOPPING
}
// Synchronized by 'this'
private State mState = State.STOPPED;
// Synchronized by 'this'
private Listener mListener;
public interface Listener {
/**
* Called when new incoming data is available.
*/
public void onNewData(byte[] data);
/**
* Called when {@link SerialInputOutputManager#run()} aborts due to an
* error.
*/
public void onRunError(Exception e);
}
/**
* Creates a new instance with no listener.
*/
public SerialInputOutputManager(UsbSerialDriver driver) {
this(driver, null);
}
/**
* Creates a new instance with the provided listener.
*/
public SerialInputOutputManager(UsbSerialDriver driver, Listener listener) {
mDriver = driver;
mListener = listener;
}
public synchronized void setListener(Listener listener) {
mListener = listener;
}
public synchronized Listener getListener() {
return mListener;
}
public void writeAsync(byte[] data) {
synchronized (mWriteBuffer) {
mWriteBuffer.put(data);
}
}
public synchronized void stop() {
if (getState() == State.RUNNING) {
Log.i(TAG, "Stop requested");
mState = State.STOPPING;
}
}
private synchronized State getState() {
return mState;
}
/**
* Continuously services the read and write buffers until {@link #stop()} is
* called, or until a driver exception is raised.
*
* NOTE(mikey): Uses inefficient read/write-with-timeout.
* TODO(mikey): Read asynchronously with {@link UsbRequest#queue(ByteBuffer, int)}
*/
@Override
public void run() {
synchronized (this) {
if (getState() != State.STOPPED) {
throw new IllegalStateException("Already running.");
}
mState = State.RUNNING;
}
Log.i(TAG, "Running ..");
try {
while (true) {
if (getState() != State.RUNNING) {
Log.i(TAG, "Stopping mState=" + getState());
break;
}
step();
}
} catch (Exception e) {
Log.w(TAG, "Run ending due to exception: " + e.getMessage(), e);
final Listener listener = getListener();
if (listener != null) {
listener.onRunError(e);
}
} finally {
synchronized (this) {
mState = State.STOPPED;
Log.i(TAG, "Stopped.");
}
}
}
private void step() throws IOException {
// Handle incoming data.
int len = mDriver.read(mReadBuffer.array(), READ_WAIT_MILLIS);
if (len > 0) {
if (DEBUG) Log.d(TAG, "Read data len=" + len);
final Listener listener = getListener();
if (listener != null) {
final byte[] data = new byte[len];
mReadBuffer.get(data, 0, len);
listener.onNewData(data);
}
mReadBuffer.clear();
}
// Handle outgoing data.
byte[] outBuff = null;
synchronized (mWriteBuffer) {
if (mWriteBuffer.position() > 0) {
len = mWriteBuffer.position();
outBuff = new byte[len];
mWriteBuffer.rewind();
mWriteBuffer.get(outBuff, 0, len);
mWriteBuffer.clear();
}
}
if (outBuff != null) {
if (DEBUG) {
Log.d(TAG, "Writing data len=" + len);
}
mDriver.write(outBuff, READ_WAIT_MILLIS);
}
}
}
| Java |
/*
* Copyright (C) 2006 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.hoho.android.usbserial.util;
/**
* Clone of Android's HexDump class, for use in debugging. Cosmetic changes
* only.
*/
public class HexDump {
private final static char[] HEX_DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
public static String dumpHexString(byte[] array) {
return dumpHexString(array, 0, array.length);
}
public static String dumpHexString(byte[] array, int offset, int length) {
StringBuilder result = new StringBuilder();
byte[] line = new byte[16];
int lineIndex = 0;
result.append("\n0x");
result.append(toHexString(offset));
for (int i = offset; i < offset + length; i++) {
if (lineIndex == 16) {
result.append(" ");
for (int j = 0; j < 16; j++) {
if (line[j] > ' ' && line[j] < '~') {
result.append(new String(line, j, 1));
} else {
result.append(".");
}
}
result.append("\n0x");
result.append(toHexString(i));
lineIndex = 0;
}
byte b = array[i];
result.append(" ");
result.append(HEX_DIGITS[(b >>> 4) & 0x0F]);
result.append(HEX_DIGITS[b & 0x0F]);
line[lineIndex++] = b;
}
if (lineIndex != 16) {
int count = (16 - lineIndex) * 3;
count++;
for (int i = 0; i < count; i++) {
result.append(" ");
}
for (int i = 0; i < lineIndex; i++) {
if (line[i] > ' ' && line[i] < '~') {
result.append(new String(line, i, 1));
} else {
result.append(".");
}
}
}
return result.toString();
}
public static String toHexString(byte b) {
return toHexString(toByteArray(b));
}
public static String toHexString(byte[] array) {
return toHexString(array, 0, array.length);
}
public static String toHexString(byte[] array, int offset, int length) {
char[] buf = new char[length * 2];
int bufIndex = 0;
for (int i = offset; i < offset + length; i++) {
byte b = array[i];
buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F];
buf[bufIndex++] = HEX_DIGITS[b & 0x0F];
}
return new String(buf);
}
public static String toHexString(int i) {
return toHexString(toByteArray(i));
}
public static byte[] toByteArray(byte b) {
byte[] array = new byte[1];
array[0] = b;
return array;
}
public static byte[] toByteArray(int i) {
byte[] array = new byte[4];
array[3] = (byte) (i & 0xFF);
array[2] = (byte) ((i >> 8) & 0xFF);
array[1] = (byte) ((i >> 16) & 0xFF);
array[0] = (byte) ((i >> 24) & 0xFF);
return array;
}
private static int toByte(char c) {
if (c >= '0' && c <= '9')
return (c - '0');
if (c >= 'A' && c <= 'F')
return (c - 'A' + 10);
if (c >= 'a' && c <= 'f')
return (c - 'a' + 10);
throw new RuntimeException("Invalid hex char '" + c + "'");
}
public static byte[] hexStringToByteArray(String hexString) {
int length = hexString.length();
byte[] buffer = new byte[length / 2];
for (int i = 0; i < length; i += 2) {
buffer[i / 2] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString
.charAt(i + 1)));
}
return buffer;
}
}
| Java |
package com.hoho.android.usbserial;
/**
* Static container of information about this library.
*/
public final class BuildInfo {
/**
* The current version of this library. Values are of the form
* "major.minor.micro[-suffix]". A suffix of "-pre" indicates a pre-release
* of the version preceeding it.
*/
public static final String VERSION = "0.2.0-pre";
private BuildInfo() {
throw new IllegalStateException("Non-instantiable class.");
}
}
| Java |
/* Copyright 2011 Google Inc.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* Project home page: http://code.google.com/p/usb-serial-for-android/
*/
package com.hoho.android.usbserial.examples;
import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.ScrollView;
import android.widget.TextView;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* A sample Activity demonstrating USB-Serial support.
*
* @author mike wakerly (opensource@hoho.com)
*/
public class DemoActivity extends Activity {
private final String TAG = DemoActivity.class.getSimpleName();
/**
* The device currently in use, or {@code null}.
*/
private UsbSerialDriver mSerialDevice;
/**
* The system's USB service.
*/
private UsbManager mUsbManager;
private TextView mTitleTextView;
private TextView mDumpTextView;
private ScrollView mScrollView;
private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();
private SerialInputOutputManager mSerialIoManager;
private final SerialInputOutputManager.Listener mListener =
new SerialInputOutputManager.Listener() {
@Override
public void onRunError(Exception e) {
Log.d(TAG, "Runner stopped.");
}
@Override
public void onNewData(final byte[] data) {
DemoActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
DemoActivity.this.updateReceivedData(data);
}
});
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mTitleTextView = (TextView) findViewById(R.id.demoTitle);
mDumpTextView = (TextView) findViewById(R.id.demoText);
mScrollView = (ScrollView) findViewById(R.id.demoScroller);
}
@Override
protected void onPause() {
super.onPause();
stopIoManager();
if (mSerialDevice != null) {
try {
mSerialDevice.close();
} catch (IOException e) {
// Ignore.
}
mSerialDevice = null;
}
}
@Override
protected void onResume() {
super.onResume();
mSerialDevice = UsbSerialProber.acquire(mUsbManager);
Log.d(TAG, "Resumed, mSerialDevice=" + mSerialDevice);
if (mSerialDevice == null) {
mTitleTextView.setText("No serial device.");
} else {
try {
mSerialDevice.open();
} catch (IOException e) {
Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
mTitleTextView.setText("Error opening device: " + e.getMessage());
try {
mSerialDevice.close();
} catch (IOException e2) {
// Ignore.
}
mSerialDevice = null;
return;
}
mTitleTextView.setText("Serial device: " + mSerialDevice);
}
onDeviceStateChange();
}
private void stopIoManager() {
if (mSerialIoManager != null) {
Log.i(TAG, "Stopping io manager ..");
mSerialIoManager.stop();
mSerialIoManager = null;
}
}
private void startIoManager() {
if (mSerialDevice != null) {
Log.i(TAG, "Starting io manager ..");
mSerialIoManager = new SerialInputOutputManager(mSerialDevice, mListener);
mExecutor.submit(mSerialIoManager);
}
}
private void onDeviceStateChange() {
stopIoManager();
startIoManager();
}
private void updateReceivedData(byte[] data) {
final String message = "Read " + data.length + " bytes: \n"
+ HexDump.dumpHexString(data) + "\n\n";
mDumpTextView.append(message);
mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
}
}
| Java |
package org.anddev.andengine.examples;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.particle.ParticleSystem;
import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter;
import org.anddev.andengine.entity.particle.initializer.AlphaInitializer;
import org.anddev.andengine.entity.particle.initializer.ColorInitializer;
import org.anddev.andengine.entity.particle.initializer.RotationInitializer;
import org.anddev.andengine.entity.particle.initializer.VelocityInitializer;
import org.anddev.andengine.entity.particle.modifier.AlphaModifier;
import org.anddev.andengine.entity.particle.modifier.ColorModifier;
import org.anddev.andengine.entity.particle.modifier.ExpireModifier;
import org.anddev.andengine.entity.particle.modifier.ScaleModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.ui.activity.LayoutGameActivity;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class XMLLayoutExample extends LayoutGameActivity {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mParticleTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected int getLayoutID() {
return R.layout.xmllayoutexample;
}
@Override
protected int getRenderSurfaceViewID() {
return R.id.xmllayoutexample_rendersurfaceview;
}
@Override
public Engine onLoadEngine() {
Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show();
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_point.png", 0, 0);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80);
final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 60, 360, this.mParticleTextureRegion);
scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
return true;
}
});
particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0));
particleSystem.addParticleInitializer(new AlphaInitializer(0));
particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10));
particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f));
particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 5));
particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3));
particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6));
particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1));
particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6));
particleSystem.addParticleModifier(new ExpireModifier(6, 6));
scene.attachChild(particleSystem);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import org.anddev.andengine.entity.scene.menu.MenuScene;
import org.anddev.andengine.entity.scene.menu.animator.SlideMenuAnimator;
import org.anddev.andengine.entity.scene.menu.item.IMenuItem;
import org.anddev.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:33:33 - 01.04.2010
*/
public class SubMenuExample extends MenuExample {
// ===========================================================
// Constants
// ===========================================================
private static final int MENU_QUIT_OK = MenuExample.MENU_QUIT + 1;
private static final int MENU_QUIT_BACK = MENU_QUIT_OK + 1;
// ===========================================================
// Fields
// ===========================================================
private MenuScene mSubMenuScene;
private BitmapTextureAtlas mSubMenuTexture;
private TextureRegion mMenuOkTextureRegion;
private TextureRegion mMenuBackTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onLoadResources() {
super.onLoadResources();
this.mSubMenuTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mMenuOkTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mSubMenuTexture, this, "menu_ok.png", 0, 0);
this.mMenuBackTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mSubMenuTexture, this, "menu_back.png", 0, 50);
this.mEngine.getTextureManager().loadTexture(this.mSubMenuTexture);
}
@Override
protected void createMenuScene() {
super.createMenuScene();
this.mSubMenuScene = new MenuScene(this.mCamera);
this.mSubMenuScene.addMenuItem(new SpriteMenuItem(MENU_QUIT_OK, this.mMenuOkTextureRegion));
this.mSubMenuScene.addMenuItem(new SpriteMenuItem(MENU_QUIT_BACK, this.mMenuBackTextureRegion));
this.mSubMenuScene.setMenuAnimator(new SlideMenuAnimator());
this.mSubMenuScene.buildAnimations();
this.mSubMenuScene.setBackgroundEnabled(false);
this.mSubMenuScene.setOnMenuItemClickListener(this);
}
@Override
public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) {
switch(pMenuItem.getID()) {
case MENU_RESET:
this.mMainScene.reset();
this.mMenuScene.back();
return true;
case MENU_QUIT:
pMenuScene.setChildSceneModal(this.mSubMenuScene);
return true;
case MENU_QUIT_BACK:
this.mSubMenuScene.back();
return true;
case MENU_QUIT_OK:
this.finish();
return true;
default:
return false;
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class SpriteExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mFaceTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
/* Calculate the coordinates for the face, so its centered on the camera. */
final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
/* Create the face and add it to the scene. */
final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion);
scene.attachChild(face);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.modifier.AlphaModifier;
import org.anddev.andengine.entity.modifier.DelayModifier;
import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.LoopEntityModifier.ILoopEntityModifierListener;
import org.anddev.andengine.entity.modifier.ParallelEntityModifier;
import org.anddev.andengine.entity.modifier.RotationByModifier;
import org.anddev.andengine.entity.modifier.RotationModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.util.modifier.IModifier;
import org.anddev.andengine.util.modifier.LoopModifier;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class EntityModifierExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mFaceTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
final Rectangle rect = new Rectangle(centerX + 100, centerY, 32, 32);
rect.setColor(1, 0, 0);
final AnimatedSprite face = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion);
face.animate(100);
face.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
final LoopEntityModifier entityModifier =
new LoopEntityModifier(
new IEntityModifierListener() {
@Override
public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
EntityModifierExample.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(EntityModifierExample.this, "Sequence started.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
EntityModifierExample.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(EntityModifierExample.this, "Sequence finished.", Toast.LENGTH_SHORT).show();
}
});
}
},
2,
new ILoopEntityModifierListener() {
@Override
public void onLoopStarted(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) {
EntityModifierExample.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(EntityModifierExample.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' started.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onLoopFinished(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) {
EntityModifierExample.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(EntityModifierExample.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' finished.", Toast.LENGTH_SHORT).show();
}
});
}
},
new SequenceEntityModifier(
new RotationModifier(1, 0, 90),
new AlphaModifier(2, 1, 0),
new AlphaModifier(1, 0, 1),
new ScaleModifier(2, 1, 0.5f),
new DelayModifier(0.5f),
new ParallelEntityModifier(
new ScaleModifier(3, 0.5f, 5),
new RotationByModifier(3, 90)
),
new ParallelEntityModifier(
new ScaleModifier(3, 5, 1),
new RotationModifier(3, 180, 0)
)
)
);
face.registerEntityModifier(entityModifier);
rect.registerEntityModifier(entityModifier.deepCopy());
scene.attachChild(face);
scene.attachChild(rect);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.PathModifier;
import org.anddev.andengine.entity.modifier.PathModifier.IPathModifierListener;
import org.anddev.andengine.entity.modifier.PathModifier.Path;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.RepeatingSpriteBackground;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.modifier.ease.EaseSineInOut;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class PathModifierExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private RepeatingSpriteBackground mGrassBackground;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mPlayerTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
Toast.makeText(this, "You move my sprite right round, right round...", Toast.LENGTH_LONG).show();
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4);
this.mGrassBackground = new RepeatingSpriteBackground(CAMERA_WIDTH, CAMERA_HEIGHT, this.mEngine.getTextureManager(), new AssetBitmapTextureAtlasSource(this, "background_grass.png"));
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
// this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(this.mGrassBackground);
/* Create the face and add it to the scene. */
final AnimatedSprite player = new AnimatedSprite(10, 10, 48, 64, this.mPlayerTextureRegion);
final Path path = new Path(5).to(10, 10).to(10, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, 10).to(10, 10);
/* Add the proper animation when a waypoint of the path is passed. */
player.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path, null, new IPathModifierListener() {
@Override
public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) {
Debug.d("onPathStarted");
}
@Override
public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) {
Debug.d("onPathWaypointStarted: " + pWaypointIndex);
switch(pWaypointIndex) {
case 0:
player.animate(new long[]{200, 200, 200}, 6, 8, true);
break;
case 1:
player.animate(new long[]{200, 200, 200}, 3, 5, true);
break;
case 2:
player.animate(new long[]{200, 200, 200}, 0, 2, true);
break;
case 3:
player.animate(new long[]{200, 200, 200}, 9, 11, true);
break;
}
}
@Override
public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) {
Debug.d("onPathWaypointFinished: " + pWaypointIndex);
}
@Override
public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity) {
Debug.d("onPathFinished");
}
}, EaseSineInOut.getInstance())));
scene.attachChild(player);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.Scene.ITouchArea;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.shape.Shape;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.extension.physics.box2d.PhysicsConnector;
import org.anddev.andengine.extension.physics.box2d.PhysicsFactory;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;
import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.sensor.accelerometer.AccelerometerData;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import android.hardware.SensorManager;
import android.widget.Toast;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 21:18:08 - 27.06.2010
*/
public class PhysicsJumpExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener, IOnAreaTouchListener {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 360;
private static final int CAMERA_HEIGHT = 240;
// ===========================================================
// Fields
// ===========================================================
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mBoxFaceTextureRegion;
private TiledTextureRegion mCircleFaceTextureRegion;
private int mFaceCount = 0;
private PhysicsWorld mPhysicsWorld;
private float mGravityX;
private float mGravityY;
private Scene mScene;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
Toast.makeText(this, "Touch the screen to add objects. Touch an object to shoot it up into the air.", Toast.LENGTH_LONG).show();
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
engineOptions.getTouchOptions().setRunOnUpdateThread(true);
return new Engine(engineOptions);
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32
this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);
this.mScene = new Scene();
this.mScene.setBackground(new ColorBackground(0, 0, 0));
this.mScene.setOnSceneTouchListener(this);
final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2);
final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2);
final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT);
final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT);
final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef);
this.mScene.attachChild(ground);
this.mScene.attachChild(roof);
this.mScene.attachChild(left);
this.mScene.attachChild(right);
this.mScene.registerUpdateHandler(this.mPhysicsWorld);
this.mScene.setOnAreaTouchListener(this);
return this.mScene;
}
@Override
public boolean onAreaTouched( final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea,final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
if(pSceneTouchEvent.isActionDown()) {
final AnimatedSprite face = (AnimatedSprite) pTouchArea;
this.jumpFace(face);
return true;
}
return false;
}
@Override
public void onLoadComplete() {
}
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
if(this.mPhysicsWorld != null) {
if(pSceneTouchEvent.isActionDown()) {
this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
return true;
}
}
return false;
}
@Override
public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) {
this.mGravityX = pAccelerometerData.getX();
this.mGravityY = pAccelerometerData.getY();
final Vector2 gravity = Vector2Pool.obtain(this.mGravityX, this.mGravityY);
this.mPhysicsWorld.setGravity(gravity);
Vector2Pool.recycle(gravity);
}
@Override
public void onResumeGame() {
super.onResumeGame();
this.enableAccelerometerSensor(this);
}
@Override
public void onPauseGame() {
super.onPauseGame();
this.disableAccelerometerSensor();
}
// ===========================================================
// Methods
// ===========================================================
private void addFace(final float pX, final float pY) {
this.mFaceCount++;
final AnimatedSprite face;
final Body body;
final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
if(this.mFaceCount % 2 == 1){
face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion);
body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef);
} else {
face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion);
body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef);
}
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true));
face.animate(new long[]{200,200}, 0, 1, true);
face.setUserData(body);
this.mScene.registerTouchArea(face);
this.mScene.attachChild(face);
}
private void jumpFace(final AnimatedSprite face) {
final Body faceBody = (Body)face.getUserData();
final Vector2 velocity = Vector2Pool.obtain(this.mGravityX * -50, this.mGravityY * -50);
faceBody.setLinearVelocity(velocity);
Vector2Pool.recycle(velocity);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.particle.ParticleSystem;
import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter;
import org.anddev.andengine.entity.particle.initializer.AlphaInitializer;
import org.anddev.andengine.entity.particle.initializer.ColorInitializer;
import org.anddev.andengine.entity.particle.initializer.RotationInitializer;
import org.anddev.andengine.entity.particle.initializer.VelocityInitializer;
import org.anddev.andengine.entity.particle.modifier.AlphaModifier;
import org.anddev.andengine.entity.particle.modifier.ColorModifier;
import org.anddev.andengine.entity.particle.modifier.ExpireModifier;
import org.anddev.andengine.entity.particle.modifier.ScaleModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class ParticleSystemSimpleExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mParticleTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show();
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_point.png", 0, 0);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80);
final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 60, 360, this.mParticleTextureRegion);
scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
return true;
}
});
particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0));
particleSystem.addParticleInitializer(new AlphaInitializer(0));
particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10));
particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f));
particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 5));
particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3));
particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6));
particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1));
particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6));
particleSystem.addParticleModifier(new ExpireModifier(6, 6));
scene.attachChild(particleSystem);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.modifier.MoveModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.scene.menu.MenuScene;
import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.anddev.andengine.entity.scene.menu.item.IMenuItem;
import org.anddev.andengine.entity.scene.menu.item.TextMenuItem;
import org.anddev.andengine.entity.scene.menu.item.decorator.ColorMenuItemDecorator;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import android.graphics.Color;
import android.view.KeyEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 01:30:15 - 02.04.2010
*/
public class TextMenuExample extends BaseExample implements IOnMenuItemClickListener {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
protected static final int MENU_RESET = 0;
protected static final int MENU_QUIT = MENU_RESET + 1;
// ===========================================================
// Fields
// ===========================================================
protected Camera mCamera;
protected Scene mMainScene;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mFaceTextureRegion;
private BitmapTextureAtlas mFontTexture;
private Font mFont;
protected MenuScene mMenuScene;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
/* Load Font/Textures. */
this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
FontFactory.setAssetBasePath("font/");
this.mFont = FontFactory.createFromAsset(this.mFontTexture, this, "Plok.ttf", 48, true, Color.WHITE);
this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
this.getFontManager().loadFont(this.mFont);
/* Load Sprite-Textures. */
this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box_menu.png", 0, 0);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mMenuScene = this.createMenuScene();
/* Just a simple scene with an animated face flying around. */
this.mMainScene = new Scene();
this.mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion);
face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight()));
this.mMainScene.attachChild(face);
return this.mMainScene;
}
@Override
public void onLoadComplete() {
}
@Override
public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) {
if(this.mMainScene.hasChildScene()) {
/* Remove the menu and reset it. */
this.mMenuScene.back();
} else {
/* Attach the menu. */
this.mMainScene.setChildScene(this.mMenuScene, false, true, true);
}
return true;
} else {
return super.onKeyDown(pKeyCode, pEvent);
}
}
@Override
public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) {
switch(pMenuItem.getID()) {
case MENU_RESET:
/* Restart the animation. */
this.mMainScene.reset();
/* Remove the menu and reset it. */
this.mMainScene.clearChildScene();
this.mMenuScene.reset();
return true;
case MENU_QUIT:
/* End Activity. */
this.finish();
return true;
default:
return false;
}
}
// ===========================================================
// Methods
// ===========================================================
protected MenuScene createMenuScene() {
final MenuScene menuScene = new MenuScene(this.mCamera);
final IMenuItem resetMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MENU_RESET, this.mFont, "RESET"), 1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f);
resetMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
menuScene.addMenuItem(resetMenuItem);
final IMenuItem quitMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MENU_QUIT, this.mFont, "QUIT"), 1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f);
quitMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
menuScene.addMenuItem(quitMenuItem);
menuScene.buildAnimations();
menuScene.setBackgroundEnabled(false);
menuScene.setOnMenuItemClickListener(this);
return menuScene;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.examples;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.SmoothCamera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.Entity;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.examples.adt.ZoomState;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.ITexture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture;
import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture.PVRTextureFormat;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.util.Debug;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 13.07.2011
*/
public class PVRTextureExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private SmoothCamera mSmoothCamera;
private ITexture mTextureRGB565;
private ITexture mTextureRGBA5551;
private ITexture mTextureARGB4444;
private ITexture mTextureRGBA888MipMaps;
private TextureRegion mHouseNearestTextureRegion;
private TextureRegion mHouseLinearTextureRegion;
private TextureRegion mHouseMipMapsNearestTextureRegion;
private TextureRegion mHouseMipMapsLinearTextureRegion;
private ZoomState mZoomState = ZoomState.NONE;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
Toast.makeText(this, "The lower houses use MipMaps!", Toast.LENGTH_LONG);
Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG);
this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) {
@Override
public void onUpdate(final float pSecondsElapsed) {
switch (PVRTextureExample.this.mZoomState) {
case IN:
this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed);
break;
case OUT:
this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed);
break;
}
super.onUpdate(pSecondsElapsed);
}
};
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera));
}
@Override
public void onLoadResources() {
try {
this.mTextureRGB565 = new PVRTexture(PVRTextureFormat.RGB_565, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) {
@Override
protected InputStream onGetInputStream() throws IOException {
return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_rgb_565);
}
};
this.mTextureRGBA5551 = new PVRTexture(PVRTextureFormat.RGBA_5551, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) {
@Override
protected InputStream onGetInputStream() throws IOException {
return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_5551);
}
};
this.mTextureARGB4444 = new PVRTexture(PVRTextureFormat.RGBA_4444, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) {
@Override
protected InputStream onGetInputStream() throws IOException {
return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_4444);
}
};
this.mTextureRGBA888MipMaps = new PVRTexture(PVRTextureFormat.RGBA_8888, new TextureOptions(GL10.GL_LINEAR_MIPMAP_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) {
@Override
protected InputStream onGetInputStream() throws IOException {
return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_8888_mipmaps);
}
};
this.mHouseNearestTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGB565, 0, 0, 512, 512, true);
this.mHouseLinearTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGBA5551, 0, 0, 512, 512, true);
this.mHouseMipMapsNearestTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureARGB4444, 0, 0, 512, 512, true);
this.mHouseMipMapsLinearTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGBA888MipMaps, 0, 0, 512, 512, true);
this.mEngine.getTextureManager().loadTextures(this.mTextureRGB565, this.mTextureRGBA5551, this.mTextureARGB4444, this.mTextureRGBA888MipMaps);
} catch (final Throwable e) {
Debug.e(e);
}
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
final int centerX = CAMERA_WIDTH / 2;
final int centerY = CAMERA_HEIGHT / 2;
final Entity container = new Entity(centerX, centerY);
container.setScale(0.5f);
container.attachChild(new Sprite(-512, -384, this.mHouseNearestTextureRegion));
container.attachChild(new Sprite(0, -384, this.mHouseLinearTextureRegion));
container.attachChild(new Sprite(-512, -128, this.mHouseMipMapsNearestTextureRegion));
container.attachChild(new Sprite(0, -128, this.mHouseMipMapsLinearTextureRegion));
scene.attachChild(container);
scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) {
if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) {
PVRTextureExample.this.mZoomState = ZoomState.IN;
} else {
PVRTextureExample.this.mZoomState = ZoomState.OUT;
}
} else {
PVRTextureExample.this.mZoomState = ZoomState.NONE;
}
return true;
}
});
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.extension.input.touch.controller.MultiTouch;
import org.anddev.andengine.extension.input.touch.controller.MultiTouchController;
import org.anddev.andengine.extension.input.touch.exception.MultiTouchException;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.MathUtils;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 00:06:23 - 11.07.2010
*/
public class AnalogOnScreenControlsExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mFaceTextureRegion;
private BitmapTextureAtlas mOnScreenControlTexture;
private TextureRegion mOnScreenControlBaseTextureRegion;
private TextureRegion mOnScreenControlKnobTextureRegion;
private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
try {
if(MultiTouch.isSupported(this)) {
engine.setTouchController(new MultiTouchController());
if(MultiTouch.isSupportedDistinct(this)) {
Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_LONG).show();
} else {
this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true;
Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
}
} catch (final MultiTouchException e) {
Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
}
return engine;
}
@Override
public void onLoadResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0);
this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0);
this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0);
this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion);
final PhysicsHandler physicsHandler = new PhysicsHandler(face);
face.registerUpdateHandler(physicsHandler);
scene.attachChild(face);
/* Velocity control (left). */
final int x1 = 0;
final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight();
final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() {
@Override
public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
physicsHandler.setVelocity(pValueX * 100, pValueY * 100);
}
@Override
public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) {
/* Nothing. */
}
});
velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
velocityOnScreenControl.getControlBase().setAlpha(0.5f);
scene.setChildScene(velocityOnScreenControl);
/* Rotation control (right). */
final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1;
final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth();
final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() {
@Override
public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
if(pValueX == x1 && pValueY == x1) {
face.setRotation(x1);
} else {
face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY)));
}
}
@Override
public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) {
/* Nothing. */
}
});
rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
rotationOnScreenControl.getControlBase().setAlpha(0.5f);
velocityOnScreenControl.setChildScene(rotationOnScreenControl);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 00:06:23 - 11.07.2010
*/
public class AnalogOnScreenControlExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mFaceTextureRegion;
private BitmapTextureAtlas mOnScreenControlTexture;
private TextureRegion mOnScreenControlBaseTextureRegion;
private TextureRegion mOnScreenControlKnobTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
Toast.makeText(this, "Also try tapping this AnalogOnScreenControl!", Toast.LENGTH_LONG).show();
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0);
this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0);
this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0);
this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion);
final PhysicsHandler physicsHandler = new PhysicsHandler(face);
face.registerUpdateHandler(physicsHandler);
scene.attachChild(face);
final AnalogOnScreenControl analogOnScreenControl = new AnalogOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, 200, new IAnalogOnScreenControlListener() {
@Override
public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
physicsHandler.setVelocity(pValueX * 100, pValueY * 100);
}
@Override
public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) {
face.registerEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.25f, 1, 1.5f), new ScaleModifier(0.25f, 1.5f, 1)));
}
});
analogOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
analogOnScreenControl.getControlBase().setAlpha(0.5f);
analogOnScreenControl.getControlBase().setScaleCenter(0, 128);
analogOnScreenControl.getControlBase().setScale(1.25f);
analogOnScreenControl.getControlKnob().setScale(1.25f);
analogOnScreenControl.refreshControlKnobPosition();
scene.setChildScene(analogOnScreenControl);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.SmoothCamera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class ZoomExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private SmoothCamera mSmoothCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mFaceTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
Toast.makeText(this, "Touch and hold the scene and the camera will smoothly zoom in.\nRelease the scene it to zoom out again.", Toast.LENGTH_LONG).show();
this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 10, 10, 1.0f);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
/* Calculate the coordinates for the screen-center. */
final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
/* Create some faces and add them to the scene. */
scene.attachChild(new Sprite(centerX - 25, centerY - 25, this.mFaceTextureRegion));
scene.attachChild(new Sprite(centerX + 25, centerY - 25, this.mFaceTextureRegion));
scene.attachChild(new Sprite(centerX, centerY + 25, this.mFaceTextureRegion));
scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
switch(pSceneTouchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
ZoomExample.this.mSmoothCamera.setZoomFactor(5.0f);
break;
case TouchEvent.ACTION_UP:
ZoomExample.this.mSmoothCamera.setZoomFactor(1.0f);
break;
}
return true;
}
});
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
import org.anddev.andengine.entity.primitive.Line;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.extension.input.touch.controller.MultiTouch;
import org.anddev.andengine.extension.input.touch.controller.MultiTouchController;
import org.anddev.andengine.extension.input.touch.exception.MultiTouchException;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.MathUtils;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class CoordinateConversionExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mFaceTextureRegion;
private Scene mScene;
private BitmapTextureAtlas mOnScreenControlTexture;
private TextureRegion mOnScreenControlBaseTextureRegion;
private TextureRegion mOnScreenControlKnobTextureRegion;
private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
Toast.makeText(this, "The arrow will always point to the left eye of the face!", Toast.LENGTH_LONG).show();
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
try {
if(MultiTouch.isSupported(this)) {
engine.setTouchController(new MultiTouchController());
if(MultiTouch.isSupportedDistinct(this)) {
Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_LONG).show();
} else {
this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true;
Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
}
} catch (final MultiTouchException e) {
Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
}
return engine;
}
@Override
public void onLoadResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0);
this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0);
this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0);
this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mScene = new Scene();
this.mScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
/* Create three lines that will form an arrow pointing to the eye. */
final Line arrowLineMain = new Line(0, 0, 0, 0, 3);
final Line arrowLineWingLeft = new Line(0, 0, 0, 0, 3);
final Line arrowLineWingRight = new Line(0, 0, 0, 0, 3);
arrowLineMain.setColor(1, 0, 0);
arrowLineWingLeft.setColor(1, 0, 0);
arrowLineWingRight.setColor(1, 0, 0);
/* Create a face-sprite. */
final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion){
@Override
protected void onManagedUpdate(final float pSecondsElapsed) {
super.onManagedUpdate(pSecondsElapsed);
final float[] eyeCoordinates = this.convertLocalToSceneCoordinates(11, 13);
final float eyeX = eyeCoordinates[VERTEX_INDEX_X];
final float eyeY = eyeCoordinates[VERTEX_INDEX_Y];
arrowLineMain.setPosition(eyeX, eyeY, eyeX, eyeY - 50);
arrowLineWingLeft.setPosition(eyeX, eyeY, eyeX - 10, eyeY - 10);
arrowLineWingRight.setPosition(eyeX, eyeY, eyeX + 10, eyeY - 10);
}
};
final PhysicsHandler physicsHandler = new PhysicsHandler(face);
face.registerUpdateHandler(physicsHandler);
face.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(3, 1, 1.75f), new ScaleModifier(3, 1.75f, 1))));
this.mScene.attachChild(face);
this.mScene.attachChild(arrowLineMain);
this.mScene.attachChild(arrowLineWingLeft);
this.mScene.attachChild(arrowLineWingRight);
/* Velocity control (left). */
final int x1 = 0;
final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight();
final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() {
@Override
public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
physicsHandler.setVelocity(pValueX * 100, pValueY * 100);
}
@Override
public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) {
/* Nothing. */
}
});
velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
velocityOnScreenControl.getControlBase().setAlpha(0.5f);
this.mScene.setChildScene(velocityOnScreenControl);
/* Rotation control (right). */
final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1;
final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth();
final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() {
@Override
public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
if(pValueX == x1 && pValueY == x1) {
face.setRotation(x1);
} else {
face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY)));
}
}
@Override
public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) {
/* Nothing. */
}
});
rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
rotationOnScreenControl.getControlBase().setAlpha(0.5f);
velocityOnScreenControl.setChildScene(rotationOnScreenControl);
return this.mScene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.Entity;
import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.ParallelEntityModifier;
import org.anddev.andengine.entity.modifier.RotationModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
import org.anddev.andengine.entity.primitive.Line;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.entity.util.ScreenCapture;
import org.anddev.andengine.entity.util.ScreenCapture.IScreenCaptureCallback;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.util.FileUtils;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class ScreenCaptureExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
Toast.makeText(this, "Touch the screen to capture it (screenshot).", Toast.LENGTH_LONG).show();
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
final ScreenCapture screenCapture = new ScreenCapture();
scene.setBackground(new ColorBackground(0, 0, 0));
/* Create three lines that will form an arrow pointing to the eye. */
final Line arrowLineMain = new Line(0, 0, 0, 0, 3);
final Line arrowLineWingLeft = new Line(0, 0, 0, 0, 3);
final Line arrowLineWingRight = new Line(0, 0, 0, 0, 3);
arrowLineMain.setColor(1, 0, 1);
arrowLineWingLeft.setColor(1, 0, 1);
arrowLineWingRight.setColor(1, 0, 1);
scene.attachChild(arrowLineMain);
scene.attachChild(arrowLineWingLeft);
scene.attachChild(arrowLineWingRight);
/* Create the rectangles. */
final Rectangle rect1 = this.makeColoredRectangle(-180, -180, 1, 0, 0);
final Rectangle rect2 = this.makeColoredRectangle(0, -180, 0, 1, 0);
final Rectangle rect3 = this.makeColoredRectangle(0, 0, 0, 0, 1);
final Rectangle rect4 = this.makeColoredRectangle(-180, 0, 1, 1, 0);
final Entity rectangleGroup = new Entity(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2);
rectangleGroup.registerEntityModifier(new LoopEntityModifier(new ParallelEntityModifier(
new SequenceEntityModifier(
new ScaleModifier(10, 1, 0.5f),
new ScaleModifier(10, 0.5f, 1)
),
new RotationModifier(20, 0, 360))
));
rectangleGroup.attachChild(rect1);
rectangleGroup.attachChild(rect2);
rectangleGroup.attachChild(rect3);
rectangleGroup.attachChild(rect4);
scene.attachChild(rectangleGroup);
/* Attaching the ScreenCapture to the end. */
scene.attachChild(screenCapture);
scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
if(pSceneTouchEvent.isActionDown()) {
final int viewWidth = ScreenCaptureExample.this.mRenderSurfaceView.getWidth();
final int viewHeight = ScreenCaptureExample.this.mRenderSurfaceView.getHeight();
screenCapture.capture(viewWidth, viewHeight, FileUtils.getAbsolutePathOnExternalStorage(ScreenCaptureExample.this, "Screen_" + System.currentTimeMillis() + ".png"), new IScreenCaptureCallback() {
@Override
public void onScreenCaptured(final String pFilePath) {
ScreenCaptureExample.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(ScreenCaptureExample.this, "Screenshot: " + pFilePath + " taken!", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onScreenCaptureFailed(final String pFilePath, final Exception pException) {
ScreenCaptureExample.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(ScreenCaptureExample.this, "FAILED capturing Screenshot: " + pFilePath + " !", Toast.LENGTH_SHORT).show();
}
});
}
});
}
return true;
}
});
return scene;
}
private Rectangle makeColoredRectangle(final float pX, final float pY, final float pRed, final float pGreen, final float pBlue) {
final Rectangle coloredRect = new Rectangle(pX, pY, 180, 180);
coloredRect.setColor(pRed, pGreen, pBlue);
final Rectangle subRectangle = new Rectangle(45, 45, 90, 90);
subRectangle.registerEntityModifier(new LoopEntityModifier(new RotationModifier(3, 0, 360)));
coloredRect.attachChild(subRectangle);
return coloredRect;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class MovingBallExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
private static final float DEMO_VELOCITY = 100.0f;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mFaceTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 0, 2, 1);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
final Ball ball = new Ball(centerX, centerY, this.mFaceTextureRegion);
final PhysicsHandler physicsHandler = new PhysicsHandler(ball);
ball.registerUpdateHandler(physicsHandler);
physicsHandler.setVelocity(DEMO_VELOCITY, DEMO_VELOCITY);
scene.attachChild(ball);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private static class Ball extends AnimatedSprite {
private final PhysicsHandler mPhysicsHandler;
public Ball(final float pX, final float pY, final TiledTextureRegion pTextureRegion) {
super(pX, pY, pTextureRegion);
this.mPhysicsHandler = new PhysicsHandler(this);
this.registerUpdateHandler(this.mPhysicsHandler);
}
@Override
protected void onManagedUpdate(final float pSecondsElapsed) {
if(this.mX < 0) {
this.mPhysicsHandler.setVelocityX(DEMO_VELOCITY);
} else if(this.mX + this.getWidth() > CAMERA_WIDTH) {
this.mPhysicsHandler.setVelocityX(-DEMO_VELOCITY);
}
if(this.mY < 0) {
this.mPhysicsHandler.setVelocityY(DEMO_VELOCITY);
} else if(this.mY + this.getHeight() > CAMERA_HEIGHT) {
this.mPhysicsHandler.setVelocityY(-DEMO_VELOCITY);
}
super.onManagedUpdate(pSecondsElapsed);
}
}
}
| Java |
package org.anddev.andengine.examples;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.AutoParallaxBackground;
import org.anddev.andengine.entity.scene.background.ParallaxBackground.ParallaxEntity;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 19:58:39 - 19.07.2010
*/
public class AutoParallaxBackgroundExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mPlayerTextureRegion;
private TiledTextureRegion mEnemyTextureRegion;
private BitmapTextureAtlas mAutoParallaxBackgroundTexture;
private TextureRegion mParallaxLayerBack;
private TextureRegion mParallaxLayerMid;
private TextureRegion mParallaxLayerFront;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4);
this.mEnemyTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "enemy.png", 73, 0, 3, 4);
this.mAutoParallaxBackgroundTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.DEFAULT);
this.mParallaxLayerFront = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "parallax_background_layer_front.png", 0, 0);
this.mParallaxLayerBack = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "parallax_background_layer_back.png", 0, 188);
this.mParallaxLayerMid = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "parallax_background_layer_mid.png", 0, 669);
this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mAutoParallaxBackgroundTexture);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5);
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerBack.getHeight(), this.mParallaxLayerBack)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-5.0f, new Sprite(0, 80, this.mParallaxLayerMid)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-10.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerFront.getHeight(), this.mParallaxLayerFront)));
scene.setBackground(autoParallaxBackground);
/* Calculate the coordinates for the face, so its centered on the camera. */
final int playerX = (CAMERA_WIDTH - this.mPlayerTextureRegion.getTileWidth()) / 2;
final int playerY = CAMERA_HEIGHT - this.mPlayerTextureRegion.getTileHeight() - 5;
/* Create two sprits and add it to the scene. */
final AnimatedSprite player = new AnimatedSprite(playerX, playerY, this.mPlayerTextureRegion);
player.setScaleCenterY(this.mPlayerTextureRegion.getTileHeight());
player.setScale(2);
player.animate(new long[]{200, 200, 200}, 3, 5, true);
final AnimatedSprite enemy = new AnimatedSprite(playerX - 80, playerY, this.mEnemyTextureRegion);
enemy.setScaleCenterY(this.mEnemyTextureRegion.getTileHeight());
enemy.setScale(2);
enemy.animate(new long[]{200, 200, 200}, 3, 5, true);
scene.attachChild(player);
scene.attachChild(enemy);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.examples.app.cityradar;
import java.util.ArrayList;
import java.util.HashMap;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.RotationModifier;
import org.anddev.andengine.entity.primitive.Line;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.Text;
import org.anddev.andengine.examples.adt.cityradar.City;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
import org.anddev.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureBuilder;
import org.anddev.andengine.opengl.texture.atlas.buildable.builder.ITextureBuilder.TextureAtlasSourcePackingException;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.sensor.location.ILocationListener;
import org.anddev.andengine.sensor.location.LocationProviderStatus;
import org.anddev.andengine.sensor.location.LocationSensorOptions;
import org.anddev.andengine.sensor.orientation.IOrientationListener;
import org.anddev.andengine.sensor.orientation.OrientationData;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.MathUtils;
import org.anddev.andengine.util.modifier.ease.EaseLinear;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
public class CityRadarActivity extends BaseGameActivity implements IOrientationListener, ILocationListener {
// ===========================================================
// Constants
// ===========================================================
private static final boolean USE_MOCK_LOCATION = false;
private static final boolean USE_ACTUAL_LOCATION = !USE_MOCK_LOCATION;
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 800;
private static final int GRID_SIZE = 80;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BuildableBitmapTextureAtlas mBuildableBitmapTextureAtlas;
private TextureRegion mRadarPointTextureRegion;
private TextureRegion mRadarTextureRegion;
private BitmapTextureAtlas mFontTexture;
private Font mFont;
private Location mUserLocation;
private final ArrayList<City> mCities = new ArrayList<City>();
private final HashMap<City, Sprite> mCityToCitySpriteMap = new HashMap<City, Sprite>();
private final HashMap<City, Text> mCityToCityNameTextMap = new HashMap<City, Text>();
private Scene mScene;
// ===========================================================
// Constructors
// ===========================================================
public CityRadarActivity() {
this.mCities.add(new City("London", 51.509, -0.118));
this.mCities.add(new City("New York", 40.713, -74.006));
// this.mCities.add(new City("Paris", 48.857, 2.352));
this.mCities.add(new City("Beijing", 39.929, 116.388));
this.mCities.add(new City("Sydney", -33.850, 151.200));
this.mCities.add(new City("Berlin", 52.518, 13.408));
this.mCities.add(new City("Rio", -22.908, -43.196));
this.mCities.add(new City("New Delhi", 28.636, 77.224));
this.mCities.add(new City("Cape Town", -33.926, 18.424));
this.mUserLocation = new Location(LocationManager.GPS_PROVIDER);
if(USE_MOCK_LOCATION) {
this.mUserLocation.setLatitude(51.518);
this.mUserLocation.setLongitude(13.408);
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public org.anddev.andengine.engine.Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CityRadarActivity.CAMERA_WIDTH, CityRadarActivity.CAMERA_HEIGHT);
return new org.anddev.andengine.engine.Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new FillResolutionPolicy(), this.mCamera));
}
@Override
public void onLoadResources() {
/* Init font. */
this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mFont = new Font(this.mFontTexture, Typeface.DEFAULT, 12, true, Color.WHITE);
this.getFontManager().loadFont(this.mFont);
this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
/* Init TextureRegions. */
this.mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(512, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mRadarTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "radar.png");
this.mRadarPointTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "radarpoint.png");
try {
this.mBuildableBitmapTextureAtlas.build(new BlackPawnTextureBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1));
} catch (final TextureAtlasSourcePackingException e) {
Debug.e(e);
}
this.mEngine.getTextureManager().loadTexture(this.mBuildableBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mScene = new Scene();
final HUD hud = new HUD();
this.mCamera.setHUD(hud);
/* BACKGROUND */
this.initBackground(hud);
/* CITIES */
this.initCitySprites();
return this.mScene;
}
private void initCitySprites() {
final int cityCount = this.mCities.size();
for(int i = 0; i < cityCount; i++) {
final City city = this.mCities.get(i);
final Sprite citySprite = new Sprite(CityRadarActivity.CAMERA_WIDTH / 2, CityRadarActivity.CAMERA_HEIGHT / 2, this.mRadarPointTextureRegion);
citySprite.setColor(0, 0.5f, 0, 1f);
final Text cityNameText = new Text(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2, this.mFont, city.getName()) {
@Override
protected void onManagedDraw(final GL10 pGL, final Camera pCamera) {
/* This ensures that the name of the city is always 'pointing down'. */
this.setRotation(-CityRadarActivity.this.mCamera.getRotation());
super.onManagedDraw(pGL, pCamera);
}
};
cityNameText.setRotationCenterY(- citySprite.getHeight() / 2);
this.mCityToCityNameTextMap.put(city, cityNameText);
this.mCityToCitySpriteMap.put(city, citySprite);
this.mScene.attachChild(citySprite);
this.mScene.attachChild(cityNameText);
}
}
private void initBackground(final IEntity pEntity) {
/* Vertical Grid lines. */
for(int i = CityRadarActivity.GRID_SIZE / 2; i < CityRadarActivity.CAMERA_WIDTH; i += CityRadarActivity.GRID_SIZE) {
final Line line = new Line(i, 0, i, CityRadarActivity.CAMERA_HEIGHT);
line.setColor(0, 0.5f, 0, 1f);
pEntity.attachChild(line);
}
/* Horizontal Grid lines. */
for(int i = CityRadarActivity.GRID_SIZE / 2; i < CityRadarActivity.CAMERA_HEIGHT; i += CityRadarActivity.GRID_SIZE) {
final Line line = new Line(0, i, CityRadarActivity.CAMERA_WIDTH, i);
line.setColor(0, 0.5f, 0, 1f);
pEntity.attachChild(line);
}
/* Vertical Grid lines. */
final Sprite radarSprite = new Sprite(CityRadarActivity.CAMERA_WIDTH / 2 - this.mRadarTextureRegion.getWidth(), CityRadarActivity.CAMERA_HEIGHT / 2 - this.mRadarTextureRegion.getHeight(), this.mRadarTextureRegion);
radarSprite.setColor(0, 1f, 0, 1f);
radarSprite.setRotationCenter(radarSprite.getWidth(), radarSprite.getHeight());
radarSprite.registerEntityModifier(new LoopEntityModifier(new RotationModifier(3, 0, 360, EaseLinear.getInstance())));
pEntity.attachChild(radarSprite);
/* Title. */
final Text titleText = new Text(0, 0, this.mFont, "-- CityRadar --");
titleText.setPosition(CAMERA_WIDTH / 2 - titleText.getWidth() / 2, titleText.getHeight() + 35);
titleText.setScale(2);
titleText.setScaleCenterY(0);
pEntity.attachChild(titleText);
}
@Override
public void onLoadComplete() {
this.refreshCitySprites();
}
@Override
protected void onResume() {
super.onResume();
this.enableOrientationSensor(this);
final LocationSensorOptions locationSensorOptions = new LocationSensorOptions();
locationSensorOptions.setAccuracy(Criteria.ACCURACY_COARSE);
locationSensorOptions.setMinimumTriggerTime(0);
locationSensorOptions.setMinimumTriggerDistance(0);
this.enableLocationSensor(this, locationSensorOptions);
}
@Override
protected void onPause() {
super.onPause();
this.mEngine.disableOrientationSensor(this);
this.mEngine.disableLocationSensor(this);
}
@Override
public void onOrientationChanged(final OrientationData pOrientationData) {
this.mCamera.setRotation(-pOrientationData.getYaw());
}
@Override
public void onLocationChanged(final Location pLocation) {
if(USE_ACTUAL_LOCATION) {
this.mUserLocation = pLocation;
}
this.refreshCitySprites();
}
@Override
public void onLocationLost() {
}
@Override
public void onLocationProviderDisabled() {
}
@Override
public void onLocationProviderEnabled() {
}
@Override
public void onLocationProviderStatusChanged(final LocationProviderStatus pLocationProviderStatus, final Bundle pBundle) {
}
// ===========================================================
// Methods
// ===========================================================
private void refreshCitySprites() {
final double userLatitudeRad = MathUtils.degToRad((float) this.mUserLocation.getLatitude());
final double userLongitudeRad = MathUtils.degToRad((float) this.mUserLocation.getLongitude());
final int cityCount = this.mCities.size();
double maxDistance = Double.MIN_VALUE;
/* Calculate the distances and bearings of the cities to the location of the user. */
for(int i = 0; i < cityCount; i++) {
final City city = this.mCities.get(i);
final double cityLatitudeRad = MathUtils.degToRad((float) city.getLatitude());
final double cityLongitudeRad = MathUtils.degToRad((float) city.getLongitude());
city.setDistanceToUser(GeoMath.calculateDistance(userLatitudeRad, userLongitudeRad, cityLatitudeRad, cityLongitudeRad));
city.setBearingToUser(GeoMath.calculateBearing(userLatitudeRad, userLongitudeRad, cityLatitudeRad, cityLongitudeRad));
maxDistance = Math.max(maxDistance, city.getDistanceToUser());
}
/* Calculate a scaleRatio so that all cities are visible at all times. */
final double scaleRatio = (CityRadarActivity.CAMERA_WIDTH / 2) / maxDistance * 0.93f;
for(int i = 0; i < cityCount; i++) {
final City city = this.mCities.get(i);
final Sprite citySprite = this.mCityToCitySpriteMap.get(city);
final Text cityNameText = this.mCityToCityNameTextMap.get(city);
final float bearingInRad = MathUtils.degToRad(90 - (float) city.getBearingToUser());
final float x = (float) (CityRadarActivity.CAMERA_WIDTH / 2 + city.getDistanceToUser() * scaleRatio * Math.cos(bearingInRad));
final float y = (float) (CityRadarActivity.CAMERA_HEIGHT / 2 - city.getDistanceToUser() * scaleRatio * Math.sin(bearingInRad));
citySprite.setPosition(x - citySprite.getWidth() / 2, y - citySprite.getHeight() / 2);
final float textX = x - cityNameText.getWidth() / 2;
final float textY = y + citySprite.getHeight() / 2;
cityNameText.setPosition(textX, textY);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
/**
* Note: Formulas taken from <a href="http://www.movable-type.co.uk/scripts/latlong.html">here</a>.
*/
private static class GeoMath {
// ===========================================================
// Constants
// ===========================================================
private static final double RADIUS_EARTH_METERS = 6371000;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* @return the distance in meters.
*/
public static double calculateDistance(final double pLatitude1, final double pLongitude1, final double pLatitude2, final double pLongitude2) {
return Math.acos(Math.sin(pLatitude1) * Math.sin(pLatitude2) + Math.cos(pLatitude1) * Math.cos(pLatitude2) * Math.cos(pLongitude2 - pLongitude1)) * RADIUS_EARTH_METERS;
}
/**
* @return the bearing in degrees.
*/
public static double calculateBearing(final double pLatitude1, final double pLongitude1, final double pLatitude2, final double pLongitude2) {
final double y = Math.sin(pLongitude2 - pLongitude1) * Math.cos(pLatitude2);
final double x = Math.cos(pLatitude1) * Math.sin(pLatitude2) - Math.sin(pLatitude1) * Math.cos(pLatitude2) * Math.cos(pLongitude2 - pLongitude1);
final float bearing = MathUtils.radToDeg((float) Math.atan2(y, x));
return (bearing + 360) % 360;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.