my app uses another projects which contains references to classes as java.beans.propertydescriptor which is not contained by android libraries.
The situation is the next: my project contains the .jar files with this another projects as libraries. I read that the solution is use an opensource class. I found it, but i dont know how can i add this class to the android .jar file. So, how can i add this class to the android java.beans library?
This is the class i have found:
package java.beans;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Vector;
import org.apache.harmony.beans.internal.nls.Messages;
public class PropertyDescriptor extends FeatureDescriptor {
private Method getter;
private Method setter;
private Class<?> propertyEditorClass;
private boolean constrained;
private boolean bound;
public PropertyDescriptor(String propertyName, Class<?> beanClass,
String getterName, String setterName) throws IntrospectionException {
super();
if (beanClass == null) {
throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$
}
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
if (setterName != null) {
if (hasMethod(beanClass, setterName)) {
setWriteMethod(beanClass, setterName);
} else {
throw new IntrospectionException(Messages.getString("beans.20")); //$NON-NLS-1$
}
}
if (getterName != null) {
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
} else {
throw new IntrospectionException(Messages.getString("beans.1F")); //$NON-NLS-1$
}
}
}
public PropertyDescriptor(String propertyName, Method getter, Method setter)
throws IntrospectionException {
super();
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
setWriteMethod(setter);
setReadMethod(getter);
}
public PropertyDescriptor(String propertyName, Class<?> beanClass)
throws IntrospectionException {
String getterName;
String setterName;
if (beanClass == null) {
throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$
}
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
getterName = createDefaultMethodName(propertyName, "is"); //$NON-NLS-1$
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
} else {
getterName = createDefaultMethodName(propertyName, "get"); //$NON-NLS-1$
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
}
}
setterName = createDefaultMethodName(propertyName, "set"); //$NON-NLS-1$
if (hasMethod(beanClass, setterName)) {
setWriteMethod(beanClass, setterName);
}
if (getter == null && setter == null) {
throw new IntrospectionException(Messages.getString(
"beans.01", propertyName)); //$NON-NLS-1$
}
}
public void setWriteMethod(Method setter) throws IntrospectionException {
if (setter != null) {
int modifiers = setter.getModifiers();
if (!Modifier.isPublic(modifiers)) {
throw new IntrospectionException(Messages.getString("beans.05")); //$NON-NLS-1$
}
Class<?>[] parameterTypes = setter.getParameterTypes();
if (parameterTypes.length != 1) {
throw new IntrospectionException(Messages.getString("beans.06")); //$NON-NLS-1$
}
Class<?> parameterType = parameterTypes[0];
Class<?> propertyType = getPropertyType();
if (propertyType != null && !propertyType.equals(parameterType)) {
throw new IntrospectionException(Messages.getString("beans.07")); //$NON-NLS-1$
}
}
this.setter = setter;
}
public void setReadMethod(Method getter) throws IntrospectionException {
if (getter != null) {
int modifiers = getter.getModifiers();
if (!Modifier.isPublic(modifiers)) {
throw new IntrospectionException(Messages.getString("beans.0A")); //$NON-NLS-1$
}
Class<?>[] parameterTypes = getter.getParameterTypes();
if (parameterTypes.length != 0) {
throw new IntrospectionException(Messages.getString("beans.08")); //$NON-NLS-1$
}
Class<?> returnType = getter.getReturnType();
if (returnType.equals(Void.TYPE)) {
throw new IntrospectionException(Messages.getString("beans.33")); //$NON-NLS-1$
}
Class<?> propertyType = getPropertyType();
if ((propertyType != null) && !returnType.equals(propertyType)) {
throw new IntrospectionException(Messages.getString("beans.09")); //$NON-NLS-1$
}
}
this.getter = getter;
}
public Method getWriteMethod() {
return setter;
}
public Method getReadMethod() {
return getter;
}
#Override
public boolean equals(Object object) {
boolean result = (object != null && object instanceof PropertyDescriptor);
if (result) {
PropertyDescriptor pd = (PropertyDescriptor) object;
boolean gettersAreEqual = (this.getter == null)
&& (pd.getReadMethod() == null) || (this.getter != null)
&& (this.getter.equals(pd.getReadMethod()));
boolean settersAreEqual = (this.setter == null)
&& (pd.getWriteMethod() == null) || (this.setter != null)
&& (this.setter.equals(pd.getWriteMethod()));
boolean propertyTypesAreEqual = this.getPropertyType() == pd
.getPropertyType();
boolean propertyEditorClassesAreEqual = this
.getPropertyEditorClass() == pd.getPropertyEditorClass();
boolean boundPropertyAreEqual = this.isBound() == pd.isBound();
boolean constrainedPropertyAreEqual = this.isConstrained() == pd
.isConstrained();
result = gettersAreEqual && settersAreEqual
&& propertyTypesAreEqual && propertyEditorClassesAreEqual
&& boundPropertyAreEqual && constrainedPropertyAreEqual;
}
return result;
}
public void setPropertyEditorClass(Class<?> propertyEditorClass) {
this.propertyEditorClass = propertyEditorClass;
}
public Class<?> getPropertyType() {
Class<?> result = null;
if (getter != null) {
result = getter.getReturnType();
} else if (setter != null) {
Class<?>[] parameterTypes = setter.getParameterTypes();
result = parameterTypes[0];
}
return result;
}
public Class<?> getPropertyEditorClass() {
return propertyEditorClass;
}
public void setConstrained(boolean constrained) {
this.constrained = constrained;
}
public void setBound(boolean bound) {
this.bound = bound;
}
public boolean isConstrained() {
return constrained;
}
public boolean isBound() {
return bound;
}
boolean hasMethod(Class<?> beanClass, String methodName) {
Method[] methods = findMethods(beanClass, methodName);
return (methods.length > 0);
}
String createDefaultMethodName(String propertyName, String prefix) {
String result = null;
if (propertyName != null) {
String bos = propertyName.substring(0, 1).toUpperCase();
String eos = propertyName.substring(1, propertyName.length());
result = prefix + bos + eos;
}
return result;
}
Method[] findMethods(Class<?> aClass, String methodName) {
Method[] allMethods = aClass.getMethods();
Vector<Method> matchedMethods = new Vector<Method>();
Method[] result;
for (Method method : allMethods) {
if (method.getName().equals(methodName)) {
matchedMethods.add(method);
}
}
result = new Method[matchedMethods.size()];
for (int j = 0; j < matchedMethods.size(); ++j) {
result[j] = matchedMethods.elementAt(j);
}
return result;
}
void setReadMethod(Class<?> beanClass, String getterName) {
boolean result = false;
Method[] getters = findMethods(beanClass, getterName);
for (Method element : getters) {
try {
setReadMethod(element);
result = true;
} catch (IntrospectionException ie) {
}
if (result) {
break;
}
}
}
void setWriteMethod(Class<?> beanClass, String setterName)
throws IntrospectionException {
boolean result = false;
Method[] setters = findMethods(beanClass, setterName);
for (Method element : setters) {
try {
setWriteMethod(element);
result = true;
} catch (IntrospectionException ie) {
}
if (result) {
break;
}
}
}
public PropertyEditor createPropertyEditor(Object bean) {
PropertyEditor editor;
if (propertyEditorClass == null) {
return null;
}
if (!PropertyEditor.class.isAssignableFrom(propertyEditorClass)) {
// beans.48=Property editor is not assignable from the
// PropertyEditor interface
throw new ClassCastException(Messages.getString("beans.48")); //$NON-NLS-1$
}
try {
Constructor<?> constr;
try {
// try to look for the constructor with single Object argument
constr = propertyEditorClass.getConstructor(Object.class);
editor = (PropertyEditor) constr.newInstance(bean);
} catch (NoSuchMethodException e) {
// try no-argument constructor
constr = propertyEditorClass.getConstructor();
editor = (PropertyEditor) constr.newInstance();
}
} catch (Exception e) {
// beans.47=Unable to instantiate property editor
RuntimeException re = new RuntimeException(
Messages.getString("beans.47"), e); //$NON-NLS-1$
throw re;
}
return editor;
}
}
Thanks.
I downloaded from this page https://code.google.com/p/openbeans/downloads/detail?name=openbeans-1.0.jar the openbean.jar. Then, i imported this jar to the project and changed the references at imported library.
Then export again the project as .jar library and import in the android project.
Related
My application is Under VAPT report certification. in my application i wrote a code for detecting weather the device is root or not. the method is returning boolean values. but they Bypassed the code with Magisk or some other root application. How to disable the bypassing???? How????
public class DeviceUtils {
public static boolean isDeviceRooted() {
return checkRootMethod1() || checkRootMethod2() || checkRootMethod3() || checkRootMethod4() || checkRootMethod5();
}
private static boolean checkRootMethod1() {
String buildTags = android.os.Build.TAGS;
return buildTags != null && buildTags.contains("test-keys");
}
private static boolean checkRootMethod2() {
String[] paths = { "/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su",
"/system/bin/failsafe/su", "/data/local/su", "/su/bin/su"};
for (String path : paths) {
if (new File(path).exists()) return true;
}
return false;
}
private static boolean checkRootMethod3() {
Process process = null;
try {
process = Runtime.getRuntime().exec(new String[] { "/system/xbin/which", "su" });
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
if (in.readLine() != null) return true;
return false;
} catch (Throwable t) {
return false;
} finally {
if (process != null) process.destroy();
}
}
private static boolean checkRootMethod4() {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
return false;
}
public static boolean findBinary(String binaryName)
{ boolean found = false;
if (!found) { String[] places = { "/sbin/", "/system/bin/", "/system/xbin/", "/data/local/xbin/", "/data/local/bin/", "/system/sd/xbin/", "/system/bin/failsafe/", "/data/local/", "/system/app/Superuser.apk", "/sbin/su", "/sbin/su/", "/system/bin/su","/system/bin/su/", "/system/xbin/su", "/system/xbin/su/", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su", "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su", "/su/", "/data/local/xbin/", "/system/bin/.ext/", "/system/bin/failsafe/", "/system/sd/xbin/", "/su/xbin/", "/su/bin/", "/magisk/.core/bin/", "/system/usr/we-need-root/", "/system/xbin/", "/system/su","/system/bin/.ext/.su","/system/usr/we-need-root/su-backup", "/system/xbin/mu", "/system/su/","/system/bin/.ext/.su/","/system/usr/we-need-root/su-backup/", "/system/xbin/mu/"};
for (String where : places)
{
if (new File(where + binaryName).exists())
{
found = true;
break;
}
}
}
return found;
}
private static boolean checkRootMethod5()
{
return findBinary("su");
}
}
I'm trying to refactoring this code
private void validate(Customer customer) {
List<String> errors = new ArrayList<>();
if (customer == null) {
errors.add("Customer must not be null");
}
if (customer != null && customer.getName() == null) {
errors.add("Name must not be null");
}
if (customer != null && customer.getName().isEmpty()) {
errors.add("Name must not be empty");
}
if (customer != null) {
Customer customerFromDb = customerRepository.findByName(customer.getName());
if (customerFromDb != null) {
errors.add("Customer already present on db");
}
}
if (!errors.isEmpty()) {
throw new ValidationException(errors);
}
}
I read this post Business logic validation patterns & advices
I'd like to build a generic validator for my entities and fields of the entity, I wrote this
private void validate(Customer customer) {
List<ValidationRule> validationRules = new ArrayList<>();
validationRules.add(new NotNullValidationRule(customer));
validationRules.add(new NotNullValidationRule(customer, Customer::getName));
validationRules.add(new NotEmptyValidationRule(customer, Customer::getName));
validationRules.add(new NotExistValidationRule(customer -> customerRepository.findByName(customer.getName())));
Validator.validate(validationRules);
}
and the Validator class
public class Validator {
public static void validate(List<ValidationRule> validationRules) {
final List<String> errors = new ArrayList<>();
for (final ValidationRule rule : validationRules) {
final Optional<String> error = rule.validate();
if (error.isPresent()) {
errors.add(error.get());
}
}
if (!errors.isEmpty()) {
throw new ValidationException(errors);
}
}
}
but I don't know how to implement the interface ValidationRule and other classes (NotNullValidationRule, NotEmptyValidationRule, NotExistValidationRule)
I would write something like :
CommonValidations.notNull(errors, customer);
if (customer != null) {
CommonValidations.notEmpty(errors, customer.getName());
}
customerCustomeBeanValidations.validName(errors, customer.getName());
customerCustomeBeanValidations.notExist(errors, customer.getName());
In the link you reference, the accepted answer suggested using the Strategy design pattern, and then gave an example of both an interface and implementation. In your case, you would create a new interface ValidationRule, with at least one method validate(), and then you would create concrete classes that each implementat that interface (NotNullValidationRule, NotEmptyValidationRule, AlreadyExistValidationRule).
I found this solution:
I create an interface ValidationRule
import java.util.Optional;
public interface ValidationRule {
Optional<ValidationError> validate();
}
And some classes that implement the behaviours
public class NotNullValidationRule implements ValidationRule {
private Object object;
private String field;
public NotNullValidationRule(Object object, String field) {
this.object = object;
if (field == null || field.isEmpty()) {
throw new IllegalArgumentException("field must not be null or emtpy");
}
this.field = field;
}
#Override public Optional<ValidationError> validate() {
if (object == null) {
return Optional.empty();
}
try {
Object value = new PropertyDescriptor(field, object.getClass()).getReadMethod().invoke(object);
if (value == null) {
ValidationError validationError = new ValidationError();
validationError.setName(object.getClass().getSimpleName() + "." + field);
validationError.setError("Field " + field + " is null");
return Optional.of(validationError);
}
}
catch (Exception e) {
throw new IllegalStateException("error during retrieve of field value");
}
return Optional.empty();
}
}
Another where I pass a method to call:
package it.winetsolutions.winactitime.core.service.validation;
import java.beans.PropertyDescriptor;
import java.util.Optional;
import java.util.function.Function;
public class NotExistValidationRule implements ValidationRule {
Object object;
String field;
Function<? super String, ? super Object> function;
public NotExistValidationRule(Object object, String field, Function<? super String, ? super Object> function) {
this.object = object;
if (field == null || field.isEmpty() || function == null) {
throw new IllegalArgumentException("field and function must not be null or emtpy");
}
this.field = field;
this.function = function;
}
#Override public Optional<ValidationError> validate() {
if (object == null) {
return Optional.empty();
}
try {
Object value = new PropertyDescriptor(field, object.getClass()).getReadMethod().invoke(object);
Long id = (Long) new PropertyDescriptor("id", object.getClass()).getReadMethod().invoke(object);
Object result = function.apply(value == null ? (String) value : ((String) value).trim());
if (result != null &&
!id.equals((Long) new PropertyDescriptor("id", result.getClass()).getReadMethod().invoke(result))) {
ValidationError validationError = new ValidationError();
validationError.setName(object.getClass().getSimpleName() + "." + field);
validationError.setError("Element with " + field +": " + value + " already exists");
return Optional.of(validationError);
}
}
catch (Exception e) {
throw new IllegalStateException("error during retrieve of field value");
}
return Optional.empty();
}
}
I am developing a voice-based app in android and facing some problems please see below code,
Java File 1
file = .wav file
public static AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException {
return getAudioInputStreamImpl(file);
}
private static AudioInputStream getAudioInputStreamImpl(Object source) throws UnsupportedAudioFileException, IOException {
GetAudioInputStreamAudioFileReaderAction action = new GetAudioInputStreamAudioFileReaderAction(source);
doAudioFileReaderIteration(action);
AudioInputStream audioInputStream = action.getAudioInputStream();
if (audioInputStream != null) {
return audioInputStream;
}
throw new UnsupportedAudioFileException("format not supported");
}
private static void doAudioFileReaderIteration(AudioFileReaderAction action) throws IOException {
Iterator audioFileReaders = TAudioConfig.getAudioFileReaders();
boolean bCompleted = false;
while (audioFileReaders.hasNext() && !bCompleted) {
AudioFileReader audioFileReader = (AudioFileReader) audioFileReaders.next();
bCompleted = action.handleAudioFileReader(audioFileReader);
}
}
Java file 2 (TAudioConfig)
public static synchronized Iterator<AudioFileReader> getAudioFileReaders() {
Iterator<AudioFileReader> it;
synchronized (TAudioConfig.class) {
it = getAudioFileReadersImpl().iterator();
}
return it;
}
private static synchronized Set<AudioFileReader> getAudioFileReadersImpl() {
Set<AudioFileReader> set;
synchronized (TAudioConfig.class) {
if (sm_audioFileReaders == null) {
sm_audioFileReaders = new ArraySet();
registerAudioFileReaders();
}
set = sm_audioFileReaders;
}
return set;
}
private static void registerAudioFileReaders() {
TInit.registerClasses(AudioFileReader.class, new C00001());
}
Java File 3 (TInit)
public static void registerClasses(Class providerClass, ProviderRegistrationAction action) {
Iterator providers = Service.providers(providerClass);
if (providers != null) {
while (providers.hasNext()) {
try {
action.register(providers.next());
} catch (Throwable e) {
}
}
}
}
Java File 4 (Service)
public static Iterator<?> providers(Class<?> cls) {
String strFullName = "com/example/voiceautomator/AudioFileReader.class";
Iterator<?> iterator = createInstancesList(strFullName).iterator();
return iterator;
}
private static List<Object> createInstancesList(String strFullName) {
List<Object> providers = new ArrayList<Object>();
Iterator<?> classNames = createClassNames(strFullName);
if (classNames != null) {
while (classNames.hasNext()) {
String strClassName = (String) classNames.next();
try {
Class<?> cls = Class.forName(strClassName, REVERSE_ORDER, ClassLoader.getSystemClassLoader());
providers.add(0, cls.newInstance());
} catch (Throwable e) {
}
}
}
return providers;
}
private static Iterator<String> createClassNames(String strFullName) {
Set<String> providers = new ArraySet<String>();
Enumeration<?> configs = null;
try {
configs = Service.class.getClassLoader().getSystemResources(strFullName);
} catch (Throwable e) {
}
if (configs != null) {
while (configs.hasMoreElements()) {
URL configFileUrl = (URL) configs.nextElement();
InputStream input = null;
try {
input = configFileUrl.openStream();
} catch (Throwable e2) {
}
if (input != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
try {
for (String strLine = reader.readLine(); strLine != null; strLine = reader.readLine()) {
strLine = strLine.trim();
int nPos = strLine.indexOf(35);
if (nPos >= 0) {
strLine = strLine.substring(0, nPos);
}
if (strLine.length() > 0) {
providers.add(strLine);
}
}
} catch (Throwable e22) {
}
}
}
}
Iterator<String> iterator = providers.iterator();
return iterator;
}
getClassLoader().getSystemResources in the Java File 4 (Service) gives me TwoEnumerationsInOne and configs.hasMoreElements() gives false so not able to go into while loop.
AudioFileReader.java is included in the package
Please guide me to resolve this issue?
Please don't forget I am working on this code in an android project
Please see the value of configs here
http://capsicumtech.in/Screenshot_1.png
Thanks in advance.
I got a bundle of code from an very old project, which they generated many redundancy methods and annotations.
Is there anyway that fast, to remove -method "doOldThing()"- from all classes in this package; remove all #AnnotationObsoluted in all class?
I know that we can use search and replace, but writing regex to delete those take a long time. I guess we could have someway to parse a Java file, then remove "doOldThings()" method, check if #AnnotationObsoluted there then remove. Any idea? Tks.
In case anyone interest, here is the code for small util that I wrote to clean up methods (by name) and import statement as well.
import com.googlecode.java2objc.main.Config;
import com.googlecode.java2objc.main.Main;
import japa.parser.ASTHelper;
import japa.parser.JavaParser;
import japa.parser.ParseException;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.ImportDeclaration;
import japa.parser.ast.body.*;
import japa.parser.ast.expr.AnnotationExpr;
import japa.parser.ast.type.ClassOrInterfaceType;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* User: lent
* Date: 10/01/2014
*/
public class CleanUpAndModelRegeneration
{
public static void main(String... args) throws IOException, ParseException
{
List<File> results =
listFilesForFolder(new File("\\LocationOfYourCode"), new ArrayList<File>());
List<String> javaFiles = new ArrayList<String>();
for (File codeFile : results)
{
// creates an input stream for the file to be parsed
FileInputStream in = new FileInputStream(codeFile);
CompilationUnit cu = null;
try
{
// parse the file
cu = JavaParser.parse(in);
removeMethod(cu, "toString");
removeMethod(cu, "append");
removeMethod(cu, "appendFields");
removeMethod(cu, "fromValue");
optimizeImport(cu);
cleanUpInterfaces("ToString", cu.getTypes());
cleanUpAnnotationForEnum(cu);
// prints the resulting compilation unit to default system output
System.out.println(cu.toString());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally
{
in.close();
}
FileOutputStream fileOutputStream = new FileOutputStream(codeFile, false);
fileOutputStream.write(cu.toString().getBytes());
fileOutputStream.flush();
javaFiles.add(codeFile.toString());
}
try
{
Config config = new Config();
Main main = new Main(config, javaFiles);
main.execute();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void cleanUpAnnotationForEnum(CompilationUnit cu)
{
for (TypeDeclaration type : cu.getTypes())
{
if (type instanceof EnumDeclaration)
{
EnumDeclaration enumDeclaration = (EnumDeclaration) type;
if (enumDeclaration.getAnnotations() != null)
{
enumDeclaration.getAnnotations().clear();
}
for (BodyDeclaration member : enumDeclaration.getMembers())
{
List<AnnotationExpr> annotations = member.getAnnotations();
if (annotations != null)
{
annotations.clear();
}
}
for (EnumConstantDeclaration member : enumDeclaration.getEntries())
{
List<AnnotationExpr> annotations = member.getAnnotations();
if (annotations != null)
{
annotations.clear();
}
}
}
}
}
private static void cleanUpInterfaces(String interfaceName, List<? extends BodyDeclaration> types)
{
for (BodyDeclaration type : types)
{
cleanUpInterface(type, interfaceName);
if (type instanceof TypeDeclaration)
{
List<BodyDeclaration> members = ((TypeDeclaration) type).getMembers();
if (members == null)
{
continue;
}
for (BodyDeclaration body : members)
{
if (body instanceof ClassOrInterfaceDeclaration)
{
cleanUpInterface(body, interfaceName);
cleanUpInterfaces(interfaceName, ((ClassOrInterfaceDeclaration) body).getMembers());
}
}
}
}
}
private static void cleanUpInterface(BodyDeclaration typeDeclaration, String interfaceName)
{
if (typeDeclaration instanceof ClassOrInterfaceDeclaration)
{
List<ClassOrInterfaceType> interfaceTypes = ((ClassOrInterfaceDeclaration) typeDeclaration).getImplements();
if (interfaceTypes == null)
{
return;
}
List<ClassOrInterfaceType> toBeRemove = new ArrayList<ClassOrInterfaceType>();
for (ClassOrInterfaceType interfaceType : interfaceTypes)
{
if (interfaceType.toString().equals(interfaceName))
{
toBeRemove.add(interfaceType);
}
}
interfaceTypes.removeAll(toBeRemove);
}
}
private static void optimizeImport(CompilationUnit cu)
{
List<ImportDeclaration> toBeRemove = new ArrayList<ImportDeclaration>();
if (cu.getImports() == null)
{
return;
}
for (ImportDeclaration importDeclaration : cu.getImports())
{
String importPackageName = importDeclaration.getName().toString();
if (importPackageName.startsWith("java.io")
|| importPackageName.startsWith("javax.xml.datatype")
|| importPackageName.startsWith("java.util")
|| importPackageName.startsWith("java.math")
|| importPackageName.startsWith("java.text"))
{
continue;
}
toBeRemove.add(importDeclaration);
}
cu.getImports().removeAll(toBeRemove);
}
public static List<File> listFilesForFolder(final File folder, List<File> result)
{
for (final File fileEntry : folder.listFiles())
{
if (fileEntry.isDirectory())
{
listFilesForFolder(fileEntry, result);
}
else
{
if (result == null)
{
result = new ArrayList<File>();
}
result.add(fileEntry);
}
}
return result;
}
private static void removeMethod(CompilationUnit cu, String methodName)
{
List<TypeDeclaration> types = cu.getTypes();
for (TypeDeclaration type : types)
{
List<BodyDeclaration> members = type.getMembers();
cleanUp(methodName, type, members);
if (type.getAnnotations() != null)
{
type.getAnnotations().clear();
}
type.setJavaDoc(null);
type.setComment(null);
}
}
private static void cleanUp(String methodName, BodyDeclaration type, List<BodyDeclaration> members)
{
List<BodyDeclaration> membersToRemove = new ArrayList<BodyDeclaration>();
for (BodyDeclaration member : members)
{
try
{
member.setJavaDoc(null);
member.setComment(null);
if (member.getAnnotations() != null)
{
member.getAnnotations().clear();
}
if (member instanceof MethodDeclaration && methodName.equals(((MethodDeclaration) member).getName()))
{
membersToRemove.add(member);
}
if (member instanceof ClassOrInterfaceDeclaration)
{
cleanUp(methodName, member, ((ClassOrInterfaceDeclaration) member).getMembers());
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
if (type instanceof TypeDeclaration)
{
((TypeDeclaration) type).getMembers().removeAll(membersToRemove);
}
else if (type instanceof ClassOrInterfaceDeclaration)
{
((ClassOrInterfaceDeclaration) type).getMembers().removeAll(membersToRemove);
}
else if (type instanceof EnumDeclaration)
{
((EnumDeclaration) type).getMembers().removeAll(membersToRemove);
}
}
private static void changeMethods(CompilationUnit cu)
{
List<TypeDeclaration> types = cu.getTypes();
for (TypeDeclaration type : types)
{
List<BodyDeclaration> members = type.getMembers();
for (BodyDeclaration member : members)
{
if (member instanceof MethodDeclaration)
{
MethodDeclaration method = (MethodDeclaration) member;
changeMethod(method);
}
}
}
}
private static void changeMethod(MethodDeclaration n)
{
// change the name of the method to upper case
n.setName(n.getName().toUpperCase());
// create the new parameter
Parameter newArg = ASTHelper.createParameter(ASTHelper.INT_TYPE, "value");
// add the parameter to the method
ASTHelper.addParameter(n, newArg);
}
}
If you erase the body of doOldThing():
doOldThing() {
}
And then inline the method, it should disappear wherever it is used. If instead you wanted to replace it with a call to doNewThing():
doOldThing() {
doNewThing();
}
and then inline.
When I use hibernate to query a ORM mapping object, It always update the object to database immediately.I've check this problem, and find it was caused by a mapping property 'appliedTestConfig'. When I remove this property from mapping file,The query operation is only query operation.
Anybody can give me some help?
The follow is a part of the mapping file.
<hibernate-mapping default-lazy="false">
<class name="cs.bean.CSBucket" table="CS_BUCKET" schema="DB2ADMIN">
<id name="bucketId" type="java.lang.Long">
<column name="BUCKET_ID" />
<generator class="native" />
</id>
<property name="bucketName" type="java.lang.String">
<column name="BUCKET_NAME" />
</property>
<property name="appliedTestConfig" type="cs.bean.AppliedTestConfig">
<column name="APPLIED_TEST_CONFIG" />
</property>
</class>
</hibernate-mapping>
The following is a part of CSBucket.java.
public class CSBucket implements java.io.Serializable {
// Fields
private Long bucketId;
private String bucketName;
private AppliedTestConfig appliedTestConfig;
public CSBucket(){
}
public Long getBucketId() {
return bucketId;
}
public void setBucketId(Long bucketId) {
this.bucketId = bucketId;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
public AppliedTestConfig getAppliedTestConfig() {
return appliedTestConfig;
}
public void setAppliedTestConfig(AppliedTestConfig appliedTestConfig) {
this.appliedTestConfig = appliedTestConfig;
}
}
The following is apart of AppliedTestConfig.java file.It is extends UserXMLType.
public class AppliedTestConfig extends UserXMLType {
private static final long serialVersionUID = 1L;
private List<String> jccDrivers = new ArrayList<String>();
private List<DB2Server> db2Servers = new ArrayList<DB2Server>();
public Serializable disassemble(Object value) throws HibernateException {
if ((value instanceof AppliedTestConfig) && value != null) {
// System.out.println("into the applied");
List<DB2Server> db2List = ((AppliedTestConfig) value)
.getDb2Servers();
List<String> jccList = ((AppliedTestConfig) value).getJccDrivers();
StringBuffer strBuf = new StringBuffer();
strBuf = strBuf.append("<applied_test_config>");
if (null != db2List && db2List.size() > 0) {
strBuf = strBuf.append("<db2server_cofig>");
for (int i = 0; i < db2List.size(); i++) {
strBuf = strBuf.append("<db2server>");
// strBuf.append(list.get(i));
DB2Server db2server = (DB2Server) db2List.get(i);
strBuf.append("<os>");
strBuf.append(db2server.getOs());
strBuf.append("</os>");
strBuf.append("<version>");
strBuf.append(db2server.getVersion());
strBuf.append("</version>");
strBuf.append("<dbcs>");
if ("".equals(db2server.getDbcs())
|| null == db2server.getDbcs()) {
strBuf.append("NULL");
} else {
strBuf.append(db2server.getDbcs());
}
strBuf.append("</dbcs>");
strBuf = strBuf.append("</db2server>");
}
strBuf = strBuf.append("</db2server_cofig>");
}
if (null != jccList && jccList.size() > 0) {
strBuf = strBuf.append("<jccdriver_config>");
for (int i = 0; i < jccList.size(); i++) {
strBuf = strBuf.append("<jccdriver>");
strBuf = strBuf.append((String) jccList.get(i));
strBuf = strBuf.append("</jccdriver>");
}
strBuf = strBuf.append("</jccdriver_config>");
}
strBuf = strBuf.append("</applied_test_config>");
return strBuf.toString();
} else
return null;
}
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
jccDrivers = new ArrayList<String>();
db2Servers = new ArrayList<DB2Server>();
if (cached != null) {
String strVal = (String) cached;
Document doc = XMLTool.loadDocumentFromStr(strVal);
if (doc != null) {
Node db2Node = XMLTool.getSingleNode(doc, "db2server_cofig");
NodeList db2NodeList = null;
if (db2Node != null) {
db2NodeList = XMLTool.getMultiNodes(db2Node, "db2server");
} else {
// Do nothing
}
Node jccNode = XMLTool.getSingleNode(doc, "jccdriver_config");
NodeList jccNodeList = null;
if (jccNode != null) {
jccNodeList = XMLTool.getMultiNodes(jccNode, "jccdriver");
} else {
// Do nothing
}
if (jccNodeList != null) {
for (int i = 0, n = jccNodeList.getLength(); i < n; i++) {
if (jccNodeList.item(i) instanceof Node) {
Node subNode = jccNodeList.item(i);
String nodeValue = XMLTool.getNodeValue(subNode);
if (nodeValue != null
&& !"".equals(nodeValue.trim())) {
jccDrivers.add(nodeValue);
}
}
}
}
// set db2Server
if (db2NodeList != null) {
for (int i = 0, n = db2NodeList.getLength(); i < n; i++) {
if (db2NodeList.item(i) instanceof Node) {
Node osNode = XMLTool.getSingleNode(db2NodeList
.item(i), "os");
Node versionNode = XMLTool.getSingleNode(
db2NodeList.item(i), "version");
Node dbcsNode = XMLTool.getSingleNode(db2NodeList
.item(i), "dbcs");
String osValue = XMLTool.getNodeValue(osNode);
String versionValue = XMLTool
.getNodeValue(versionNode);
String dbcsValue = XMLTool.getNodeValue(dbcsNode);
DB2Server db2server = new DB2Server(osValue,
versionValue, dbcsValue);
db2Servers.add(db2server);
}
}
}
}
}
AppliedTestConfig one = new AppliedTestConfig();
one.setDb2Servers(db2Servers);
one.setJccDrivers(jccDrivers);
return one;
}
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (x != null && y != null) {
// todo: to modify this to detail equal
return x.equals(y);
}
return false;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((db2Servers == null) ? 0 : db2Servers.hashCode());
result = prime * result
+ ((jccDrivers == null) ? 0 : jccDrivers.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AppliedTestConfig other = (AppliedTestConfig) obj;
if (db2Servers == null) {
if (other.db2Servers != null)
return false;
} else if (!db2Servers.equals(other.db2Servers))
return false;
if (jccDrivers == null) {
if (other.jccDrivers != null)
return false;
} else if (!jccDrivers.equals(other.jccDrivers))
return false;
return true;
}
/**
* Generate Getters and Setters....
* */
}
The following is UserXMLType file
public abstract class UserXMLType implements UserType, Serializable {
private static final long serialVersionUID = 1L;
private static final int[] TYPES = new int[] { Types.VARCHAR };
public int[] sqlTypes() {
return TYPES;
}
public Class returnedClass() {
// TODO Auto-generated method stub
System.out.println("===>>>return Class is : " + this.getClass());
return this.getClass();
}
public abstract boolean equals(Object first, Object second) throws HibernateException ;
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
System.out.println("===>>>nullSafeGet is executed.");
String value = (String) Hibernate.STRING.nullSafeGet(rs, names[0]);
if (value != null) {
return assemble(value,owner);
} else {
return null;
}
}
public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
System.out.println("===>>>nullSafeSet is executed.");
if (value != null) {
Serializable str =disassemble(value);
Hibernate.STRING.nullSafeSet(st, str, index);
} else {
Hibernate.STRING.nullSafeSet(st, value, index);
}
}
public Object deepCopy(Object value) throws HibernateException {
System.out.println("===>>>deepCopy is executed.");
Object result=null;
// dingk *
//if (value==null) return "";
if (value==null) return null;
if (!(value instanceof Serializable)) {
throw new HibernateException("Clone锟侥讹拷锟斤拷锟斤拷锟绞碉拷锟絡ava.io.Serializable锟接口o拷");
}
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = null;
ObjectInputStream oi = null;
try {
oo = new ObjectOutputStream(bo);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oo.writeObject(value);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
try {
oi = new ObjectInputStream(bi);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
result = oi.readObject();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public boolean isMutable() {
return false;
}
public int hashCode(Object arg0) throws HibernateException {
// TODO Auto-generated method stub
return arg0.hashCode();
}
public abstract Serializable disassemble(Object obj) throws HibernateException ;
public abstract Object assemble(Serializable value, Object owner) throws HibernateException;
public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {
if (arg0==null) return null;
if(this.isMutable()){
return deepCopy(arg0);
}
else{
return arg0;
}
}
}
The following is the console output when i query a CSBucket.
[13-5-16 15:32:50:109 CST] 00000022 SystemOut O Hibernate:
select
csbucket0_.BUCKET_ID as BUCKET1_57_,
csbucket0_.BUCKET_NAME as BUCKET2_57_,
csbucket0_.LOC_IN_CMVC as LOC3_57_,
csbucket0_.OWNER as OWNER57_,
csbucket0_.ORIGINATOR as ORIGINATOR57_,
csbucket0_.IS_MANUAL as IS6_57_,
csbucket0_.BUCKET_TYPE as BUCKET7_57_,
csbucket0_.RUN_TYPE as RUN8_57_,
csbucket0_.CUSTOMIZE as CUSTOMIZE57_,
csbucket0_.ONLINE_CHECK as ONLINE10_57_,
csbucket0_.LINE_ITEM_DCR as LINE11_57_,
csbucket0_.STORE_UDFS_LOC as STORE12_57_,
csbucket0_.BUCKET_CLASS as BUCKET13_57_,
csbucket0_.DESCRIPTION as DESCRIP14_57_,
csbucket0_.DB_LUW as DB15_57_,
csbucket0_.DB_ZOS as DB16_57_,
csbucket0_.JCLS_NEEDED as JCLS17_57_,
csbucket0_.INPUT_FILE_LOC as INPUT18_57_,
csbucket0_.UTLITITES as UTLITITES57_,
csbucket0_.TEST_FOCUS as TEST20_57_,
csbucket0_.TC_NO as TC21_57_,
csbucket0_.MAIN_FUNCTION as MAIN22_57_,
csbucket0_.MAX_TIME as MAX23_57_,
csbucket0_.OTHER_INSTRUCT as OTHER24_57_,
csbucket0_.ACTIVE_STATUS as ACTIVE25_57_,
csbucket0_.CREATOR as CREATOR57_,
csbucket0_.UPDATOR as UPDATOR57_,
csbucket0_.ACTIVATOR as ACTIVATOR57_,
csbucket0_.PRE_BUCKET_ID as PRE29_57_,
csbucket0_.CERTAIN_JCC as CERTAIN30_57_,
csbucket0_.APPLIED_RELEASE as APPLIED31_57_,
csbucket0_.APPLIED_TEST_CONFIG as APPLIED32_57_,
csbucket0_.APPLIED_JDK as APPLIED33_57_,
csbucket0_.TXT_PARM as TXT34_57_,
csbucket0_.BUCKET_RUN as BUCKET35_57_,
csbucket0_.BUCKET_FILE as BUCKET36_57_
from
DB2ADMIN.CS_BUCKET csbucket0_
where
csbucket0_.BUCKET_NAME like '%xml_index_aps_qad_j01%'
[13-5-16 15:32:52:250 CST] 00000022 SystemOut O ===>>>nullSafeGet is executed.
[13-5-16 15:32:52:640 CST] 00000022 SystemOut O ===>>>deepCopy is executed.
[13-5-16 15:32:52:828 CST] 00000022 SystemOut O Hibernate:
update
DB2ADMIN.CS_BUCKET
set
BUCKET_NAME=?,
LOC_IN_CMVC=?,
OWNER=?,
ORIGINATOR=?,
IS_MANUAL=?,
BUCKET_TYPE=?,
RUN_TYPE=?,
CUSTOMIZE=?,
ONLINE_CHECK=?,
LINE_ITEM_DCR=?,
STORE_UDFS_LOC=?,
BUCKET_CLASS=?,
DESCRIPTION=?,
DB_LUW=?,
DB_ZOS=?,
JCLS_NEEDED=?,
INPUT_FILE_LOC=?,
UTLITITES=?,
TEST_FOCUS=?,
TC_NO=?,
MAIN_FUNCTION=?,
MAX_TIME=?,
OTHER_INSTRUCT=?,
ACTIVE_STATUS=?,
CREATOR=?,
UPDATOR=?,
ACTIVATOR=?,
PRE_BUCKET_ID=?,
CERTAIN_JCC=?,
APPLIED_RELEASE=?,
APPLIED_TEST_CONFIG=?,
APPLIED_JDK=?,
TXT_PARM=?,
BUCKET_RUN=?,
BUCKET_FILE=?
where
BUCKET_ID=?
[13-5-16 15:32:52:953 CST] 00000022 SystemOut O ===>>>nullSafeSet is executed.
[13-5-16 15:32:53:171 CST] 00000022 SystemOut O ===>>>deepCopy is executed.
Now,anybody can help me to make a query operation not to update database ? Thanks very much.