Error in Preview of Custom Eclipse refactoring - java

I am implementing an new eclipse refactoring. This will enable developers to Pull-up the preconditions statements from a child method to the parent method.
This all works perfectly when I select "Finish" in the refactoring wizard, but when I select "Preview" I get an error "No target edit provided." This seems to be caused by a problem in the TextEdit returned from ASTRewrite.rewriteAST(). However I cannot figure out why.
The stack trace of the exception happens after my Refactoring.createChange() code is run, and the change is used to generate the preview.
org.eclipse.text.edits.MalformedTreeException: No target edit provided.
at org.eclipse.text.edits.MoveSourceEdit.performConsistencyCheck(MoveSourceEdit.java:208)
at org.eclipse.text.edits.TextEdit.traverseConsistencyCheck(TextEdit.java:873)
at org.eclipse.text.edits.MoveSourceEdit.traverseConsistencyCheck(MoveSourceEdit.java:183)
at org.eclipse.text.edits.TextEdit.traverseConsistencyCheck(TextEdit.java:869)
at org.eclipse.text.edits.TextEdit.traverseConsistencyCheck(TextEdit.java:869)
at org.eclipse.text.edits.TextEditProcessor.checkIntegrityDo(TextEditProcessor.java:176)
at org.eclipse.text.edits.TextEdit.dispatchCheckIntegrity(TextEdit.java:743)
at org.eclipse.text.edits.TextEditProcessor.performEdits(TextEditProcessor.java:151)
at org.eclipse.ltk.core.refactoring.TextChange.getPreviewDocument(TextChange.java:534)
at org.eclipse.ltk.core.refactoring.TextChange.getPreviewDocument(TextChange.java:403)
at org.eclipse.ltk.core.refactoring.TextChange.getPreviewContent(TextChange.java:411)
at org.eclipse.ltk.internal.ui.refactoring.TextEditChangePreviewViewer.setInput(TextEditChangePreviewViewer.java:209)
at org.eclipse.ltk.internal.ui.refactoring.AbstractChangeNode.feedInput(AbstractChangeNode.java:99)
at org.eclipse.ltk.internal.ui.refactoring.PreviewWizardPage.showPreview(PreviewWizardPage.java:598)
at org.eclipse.ltk.internal.ui.refactoring.PreviewWizardPage.access$6(PreviewWizardPage.java:583)
at org.eclipse.ltk.internal.ui.refactoring.PreviewWizardPage$7.selectionChanged(PreviewWizardPage.java:574)
at org.eclipse.jface.viewers.Viewer$2.run(Viewer.java:162)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.runtime.Platform.run(Platform.java:888)
at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:48)
at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java:160)
at org.eclipse.jface.viewers.StructuredViewer.updateSelection(StructuredViewer.java:2132)
at org.eclipse.jface.viewers.StructuredViewer.setSelection(StructuredViewer.java:1669)
at org.eclipse.jface.viewers.TreeViewer.setSelection(TreeViewer.java:1124)
at org.eclipse.jface.viewers.Viewer.setSelection(Viewer.java:392)
at org.eclipse.ltk.internal.ui.refactoring.PreviewWizardPage.setVisible(PreviewWizardPage.java:505)
at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.makeVisible(RefactoringWizardDialog2.java:762)
at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.showCurrentPage(RefactoringWizardDialog2.java:477)
at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.nextOrPreviewPressed(RefactoringWizardDialog2.java:507)
at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.access$2(RefactoringWizardDialog2.java:492)
at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2$1.widgetSelected(RefactoringWizardDialog2.java:691)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:228)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1003)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3880)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3473)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
at org.eclipse.jface.window.Window.open(Window.java:801)
at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation$1.run(RefactoringWizardOpenOperation.java:143)
at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:155)
at org.jmlspecs.eclipse.refactor.action.AbstractMethodActionDelegate.run(AbstractMethodActionDelegate.java:78)
at org.jmlspecs.eclipse.refactor.action.AbstractMethodActionDelegate.run(AbstractMethodActionDelegate.java:67)
at org.eclipse.ui.internal.PluginAction.runWithEvent(PluginAction.java:251)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:452)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1003)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3880)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3473)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2405)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2369)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2221)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:500)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:493)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:113)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:194)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:368)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:559)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:514)
at org.eclipse.equinox.launcher.Main.run(Main.java:1311)
at org.eclipse.equinox.launcher.Main.main(Main.java:1287)
Currently the code that performs the change looks like this:
CompilationUnit sourceNode = ...
ASTRewrite sourceRewrite = ASTRewrite.create(sourceNode.getAST());
Statement statement = ...
sourceRewrite.createMoveTarget(statement);
CompilationUnit destinationNode = ...
MethodDeclaration destinationMethod = ...
ASTRewrite destinationRewrite = ASTRewrite.create(destinationNode.getAST());
ListRewrite lrw = destinationRewrite.getListRewrite(destinationMethod.getBody(),
Block.STATEMENTS_PROPERTY);
lrw.insertFirst(statement, null);
I know that the way createMoveTarget is used is not how it is documented, but when I follow the documentation like below, the statement is deleted from the source but not moved to the destination and I still get the same error in the preview.
CompilationUnit sourceNode = ...
ASTRewrite sourceRewrite = ASTRewrite.create(sourceNode.getAST());
Statement statement = ...
Statement replacement = sourceRewrite.createMoveTarget(statement);
sourceRewrite.remove(statement, null);
CompilationUnit destinationNode = ...
MethodDeclaration destinationMethod = ...
ASTRewrite destinationRewrite = ASTRewrite.create(destinationNode.getAST());
ListRewrite lrw = destinationRewrite.getListRewrite(destinationMethod.getBody(),
Block.STATEMENTS_PROPERTY);
lrw.insertFirst(replacement, null);
Here is an example of the Refactoring being performed.
Before:
class A {
foo(int a) {
return a * 2;
}
}
class B {
foo(int a) {
JC.requires(a > 1);
return a * 3;
}
}
After:
class A {
foo(int a) {
JC.requires(a > 1);
return a * 2;
}
}
class B extends A {
foo(int a) {
return a * 3;
}
}

I found the eclipse.org article the most helpful to get me started.
A good place to get started debugging the code is to set breakpoints on org.eclipse.jdt.core.dom.rewrite.ASTRewrite, particularly the rewriteAST() method, then trigger some refactorings.
Here are a few you might find useful. Are you looking for anything in particular or a general sense of how to process the AST?
http://www.ibm.com/developerworks/opensource/library/os-ast/
http://blog.sahits.ch/?p=228
http://www.vogella.com/articles/EclipseJDT/article.html

Related

Creating a transformer to add a class from an agent using ByteBuddy

I am trying to load classes from an agent implemented using ByteBuddy. I have a class defined in the agent and want to load it in the target program. here is what my transformer looks like:
public class ClassLoaderTransformer implements AgentBuilder.Transformer {
private final Class<?> targetClass;
public ClassLoaderTransformer(Class<?> targetClass) {
this.targetClass = targetClass;
}
#Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
try {
final Class<?> aClass = Class.forName(typeDescription.getName());
resolveClassLoadingStrategy(aClass).load(classLoader, singletonMap(
new TypeDescription.ForLoadedType(targetClass),
ClassFileLocator.ForClassLoader.read(targetClass)
));
} catch (Exception e){
System.out.println("Something went terribly wrong: " + e.getMessage());
}
return builder;
}
private static ClassLoadingStrategy<ClassLoader> resolveClassLoadingStrategy(Class<?> targetClass) throws IllegalAccessException {
if ( !ClassInjector.UsingLookup.isAvailable() ) {
return new ClassLoadingStrategy.ForUnsafeInjection(targetClass.getProtectionDomain() );
}
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandles.Lookup privateLookup = MethodHandles.privateLookupIn(targetClass, lookup);
return ClassLoadingStrategy.UsingLookup.of( privateLookup );
}
}
However, this code is not working. It throws the following error:
tech.ikora.seleniumagent.helpers.SourcePageFetcher must be defined in the same package as org.openqa.selenium.remote.RemoteWebDriver
and the stack traces looks like this:
java.lang.IllegalArgumentException: tech.ikora.seleniumagent.helpers.SourcePageFetcher must be defined in the same package as org.openqa.selenium.remote.RemoteWebDriver
at net.bytebuddy.dynamic.loading.ClassInjector$UsingLookup.injectRaw(ClassInjector.java:1414)
at net.bytebuddy.dynamic.loading.ClassInjector$AbstractBase.inject(ClassInjector.java:110)
at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$UsingLookup.load(ClassLoadingStrategy.java:492)
at tech.ikora.seleniumagent.ClassLoaderTransformer.transform(ClassLoaderTransformer.java:27)
at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.doTransform(AgentBuilder.java:10364)
at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.transform(AgentBuilder.java:10302)
at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.access$1600(AgentBuilder.java:10068)
at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer$Java9CapableVmDispatcher.run(AgentBuilder.java:10761)
at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer$Java9CapableVmDispatcher.run(AgentBuilder.java:10699)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.transform(AgentBuilder.java:10258)
at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer$ByteBuddy$ModuleSupport.transform(Unknown Source)
at java.instrument/sun.instrument.TransformerManager.transform(TransformerManager.java:188)
at java.instrument/sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:563)
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
at java.base/java.net.URLClassLoader.defineClass(URLClassLoader.java:515)
at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:423)
at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:417)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:689)
at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:416)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:588)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at org.apache.maven.surefire.booter.IsolatedClassLoader.loadClass(IsolatedClassLoader.java:97)
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
at java.base/java.net.URLClassLoader.defineClass(URLClassLoader.java:515)
at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:423)
at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:417)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:689)
at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:416)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:588)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at org.apache.maven.surefire.booter.IsolatedClassLoader.loadClass(IsolatedClassLoader.java:97)
at base.BaseTest.setup(BaseTest.java:31)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:132)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:61)
at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:366)
at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:320)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:176)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:122)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.testng.TestRunner.privateRun(TestRunner.java:764)
at org.testng.TestRunner.run(TestRunner.java:585)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1218)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.runSuites(TestNG.java:1069)
at org.testng.TestNG.run(TestNG.java:1037)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:77)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeMulti(TestNGDirectoryTestSuite.java:159)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:99)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:106)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.plugin.surefire.InPluginVMSurefireStarter.runSuitesInProcess(InPluginVMSurefireStarter.java:80)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:724)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAllProviders(AbstractSurefireMojo.java:682)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:648)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:586)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:193)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)
In this example, SourcePageFetcher is the targetClass and RemoveWebDriver is the class provided by the TypeDescription.
The goal of this class loader is to load classes that would be helpers to some of the Advice that I created to instrument my code. Should I try to use the ClassInjector in another way? Or am I seeing the problem in the wrong way or should I just use another ClassLoadingStrategy?
Following #RafaelWinterhalter suggestion, The solution that worked for me was to use the ClassInjector with UsingUnsafe. This lead to the following working code:
public class ClassLoaderTransformer implements AgentBuilder.Transformer {
private final Class<?> targetClass;
public ClassLoaderTransformer(Class<?> targetClass) {
this.targetClass = targetClass;
}
#Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
try {
ClassInjector.UsingUnsafe.ofBootLoader().inject(singletonMap(
new TypeDescription.ForLoadedType(targetClass),
ClassFileLocator.ForClassLoader.read(targetClass)
));
} catch (Throwable e){
System.out.println("Something went terribly wrong: " + e.getMessage());
}
return builder;
}
}
Note that in this case, the class is loading in the boot class loader, hence we should try to keep the classes loaded there as simple as possible. Furthermore, the classes loaded here seem to not have access to classes loaded by the children class loader, so again, I had to keep the classes to the bear minimal.
As the error message suggests: a lookup only allows you to define classes in packages of the specified lookup's class. If the package differs as it does for you:
tech.ikora.seleniumagent.helpers
org.openqa.selenium.remote
the JVM would not allow for it. From an agent, you can however also use the UsingUnsafe strategy as the Instrumentation instance can grant you access to the JVM internals. Otherwise, you'd need to hook your injection to a class in the right package.
Note that you can rather use the ClassInjector directly instead of using a ClassLoadingStrategy.

Srping/ Hibernate: spring.entity.Downloads cannot be cast to java.lang.Integer

I have recently started trying to learn java and finished a spring/hibernate course in aims to implement a solution to some problems at work in my spare time. Needless to say, I have hit a snag.
I am wondering if anyone can see anything obviously wrong with the code attached below that can cause the following error:
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/sonya-local] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: com.sonya.spring.entity.Downloads cannot be cast to java.lang.Integer] with root cause
java.lang.ClassCastException: com.sonya.spring.entity.Downloads cannot be cast to java.lang.Integer
at org.hibernate.type.descriptor.java.IntegerTypeDescriptor.unwrap(IntegerTypeDescriptor.java:19)
at org.hibernate.type.descriptor.sql.IntegerTypeDescriptor$1.doBind(IntegerTypeDescriptor.java:46)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:74)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:277)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:272)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:53)
at org.hibernate.hql.internal.ast.exec.BasicExecutor.doExecute(BasicExecutor.java:82)
at org.hibernate.hql.internal.ast.exec.BasicExecutor.execute(BasicExecutor.java:59)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:429)
at org.hibernate.engine.query.spi.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:374)
at org.hibernate.internal.SessionImpl.executeUpdate(SessionImpl.java:1495)
at org.hibernate.query.internal.AbstractProducedQuery.doExecuteUpdate(AbstractProducedQuery.java:1507)
at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1485)
at com.sonya.spring.dao.DownloadsDAOImpl.archiveProduct(DownloadsDAOImpl.java:128)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy50.archiveProduct(Unknown Source)
at com.sonya.spring.service.DownloadsServiceImpl.archiveProduct(DownloadsServiceImpl.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
Basically I am looking to move data between tables after a small vetting period (1 hour) I have successfully added timestamps and a few other functions such as search, api calls etc so far.
The end goal of this is to attach a scheduler and have it run periodically throughout the day but for now I have added a url mapping to trigger it manually.
When hitting the URL I receive the above error:
My Code:
Controller code
#GetMapping("/archiveproducts")
public String archiveDownloads (){
List<Downloads> theDownloads = downloadsService.getDownloads();
for (Downloads archiveDownload : theDownloads) {
// display the download ... just for clarity
System.out.println(archiveDownload);
Date timer = new Date();
Date purge = archiveDownload.getTimestamp();
long hours = (timer.getTime() - purge.getTime()) / DateTimeConstants.MILLIS_PER_HOUR;
if (hours >= 1) {
downloadsService.archiveProduct(archiveDownload);
}
}
return "list-downloads";
}
DownloadsDAOimpl Code: (java:128)
public List<Downloads> archiveProduct(Downloads archiveDownload) {
Session currentSession = sessionFactory.getCurrentSession();
Query theCopyQuery =
currentSession.createQuery("insert into Archive(fieldOne, fieldTwo, fieldThree, fieldFour, fieldFive, , fieldSix, FieldSeven)"
+ "sfieldOne, fieldTwo, fieldThree, fieldFour, fieldFive, , fieldSix, FieldSeven from Downloads where id=:theId");
theCopyQuery.setParameter("theId", archiveDownload);
theCopyQuery.executeUpdate();
List<Downloads> archiveProducts = theCopyQuery.getResultList();
Query theDeleteQuery =
currentSession.createQuery("delete from Downloads where id=:theId");
theDeleteQuery.setParameter("theId", archiveDownload);
theDeleteQuery.executeUpdate();
// return the results
return archiveProducts;
}
DownloadsServiceImpl.java:65
#Override
#Transactional
public List<Downloads> archiveProduct(Downloads archiveDownload) {
return downloadsDAO.archiveProduct(archiveDownload);
}
I understand that it's telling me I cannot cast an entity as an integer. but I don't understand where this integer is coming from or how to fix/reslove it.. I have a used a similar code approach for one of the API's and it worked okay.
#PostMapping("/listdownloads")
public List<Downloads> addDownloads (#RequestBody List<Downloads> theDownloads){
for (Downloads tempDownload : theDownloads) {
// display the download ... just for clarity
tempDownload.setId(0);
tempDownload.setTimestamp(null);
System.out.println(tempDownload);
// save to the database
downloadsService.saveProduct(tempDownload);
}
Cheers,
Danny
I think the issue is with this line.
theDeleteQuery.setParameter("theId", archiveDownload);
It is expecting an integer as Id but you passing Downloads object as mentioned in eror message. you can try something like this.
theDeleteQuery.setParameter("theId", archiveDownload.getId());

"duplicate class definition bug occured" using jaxb in jboss

I'm using jaxb inside a jboss 5.0.1GA container, and seeing a strange exception at startup. It appears once only.
From the stacktrace you can see that it is during the class initialisation of FrameworkUtil class.
FrameworkUtil line 119 looks like this:
JAXBContext j = JAXBContext.newInstance(Validate.class, Response.class ....<more classes>);
Validate.java has this in it:
#XmlRootElement(name="validate")
public class Validate {
List<String> userGroups;
#XmlElementWrapper(name="userGroups")
#XmlElement(name="item")
public String[] getUserGroups() {
if (userGroups != null) {
return userGroups.toArray(new String[userGroups.size()]);
}
else return null;
}
public void setUserGroups(String[] userGrps) {
userGroups = new ArrayList<String>();
if (userGrps != null) {
for (String userGrp : userGrps) {
userGroups.add(new String(userGrp));
}
}
}
}
In the stack trace is a reference to Validate. But sometimes the stacktrace is different, and refers to the same field (userGroups) in Response.class instead.
Here's the stack trace:
Mar 19, 2015 11:20:50 AM com.sun.xml.bind.v2.runtime.reflect.opt.Injector inject
WARNING: duplicate class definition bug occured? Please report this : com/mycompany/ecommerce/message/beans/Validate$JaxbAccessorM_getUserGroups_setUserGroups_[Ljava_lang_String;
java.lang.ClassFormatError: Illegal class name "com/mycompany/ecommerce/message/beans/Validate$JaxbAccessorM_getUserGroups_setUserGroups_[Ljava_lang_String;" in class file com/mycompany/ecommerce/messa
ge/beans/Validate$JaxbAccessorM_getUserGroups_setUserGroups_[Ljava_lang_String;
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.lang.ClassLoader.defineClass(ClassLoader.java:643)
at sun.reflect.GeneratedMethodAccessor209.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.inject(Injector.java:205)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.inject(Injector.java:85)
at com.sun.xml.bind.v2.runtime.reflect.opt.AccessorInjector.prepare(AccessorInjector.java:89)
at com.sun.xml.bind.v2.runtime.reflect.opt.OptimizedAccessorFactory.get(OptimizedAccessorFactory.java:114)
at com.sun.xml.bind.v2.runtime.reflect.Accessor$GetterSetterReflection.optimize(Accessor.java:369)
at com.sun.xml.bind.v2.runtime.property.ArrayProperty.<init>(ArrayProperty.java:65)
at com.sun.xml.bind.v2.runtime.property.ArrayERProperty.<init>(ArrayERProperty.java:84)
at com.sun.xml.bind.v2.runtime.property.ArrayElementProperty.<init>(ArrayElementProperty.java:96)
at com.sun.xml.bind.v2.runtime.property.ArrayElementLeafProperty.<init>(ArrayElementLeafProperty.java:66)
at sun.reflect.GeneratedConstructorAccessor172.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:124)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:179)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:515)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:330)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1140)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:154)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:121)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:248)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:235)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:432)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:637)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)
at com.mycompany.global.er.util.FrameworkUtil.<clinit>(FrameworkUtil.java:119)
Did you check this bug out ?
Seems to be fixed in version 2.2.11 of jaxb implementation.
Maybe you could try and replace jaxb JAR files, they're probably in you server's lib, unless your webapp overwrites them in it's own lib folder.
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>

classcast exception in change font

I wanted to change font for a text field from Window->prefernce->change font option. I implemented the code.
But what happens is while updating the text field I am getting following classcast exception. Following is the code for adding the font dialog in Preference
public class SampleViewPreferencePage extends FieldEditorPreferencePage implements
IWorkbenchPreferencePage {
public SampleViewPreferencePage() {
super(GRID);
}
public void createFieldEditors() {
addField(new FontFieldEditor("font", "Font selection",
getFieldEditorParent()));
}
#Override
public void init(IWorkbench workbench) {
setPreferenceStore(SvtActivator.getDefault().getPreferenceStore());
}
}
SampleView-> createPartControl()
/**
* This is a callback that will allow us to create the viewer and initialize
* it.
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
FillLayout layout = new FillLayout();
layout.marginHeight = layout.marginWidth = 10;
parent.setLayout(layout);
text = new StyledText(parent, SWT.V_SCROLL | SWT.H_SCROLL
| SWT.MULTI | SWT.BORDER);
text.setText("");
}
#Override
public void propertyChange(org.eclipse.jface.util.PropertyChangeEvent event) {
System.out.println("Value changed..");
Object newValue = event.getNewValue();
System.out.println("newValue: "+newValue);
//if (newValue instanceof FontData) {
Font font = new Font(Display.getCurrent(),
(FontData) newValue);
getText().setFont(font);
//}
}
java.lang.ClassCastException: [Lorg.eclipse.swt.graphics.FontData; cannot be cast to org.eclipse.swt.graphics.FontData
at com.example.MyView.propertyChange(MyView.java:111)
at org.eclipse.ui.preferences.ScopedPreferenceStore$3.run(ScopedPreferenceStore.java:375)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.ui.preferences.ScopedPreferenceStore.firePropertyChangeEvent(ScopedPreferenceStore.java:372)
at org.eclipse.jface.preference.PreferenceConverter.setValue(PreferenceConverter.java:463)
at org.eclipse.jface.preference.FontFieldEditor.doStore(FontFieldEditor.java:242)
at org.eclipse.jface.preference.FieldEditor.store(FieldEditor.java:680)
at org.eclipse.jface.preference.FieldEditorPreferencePage.performOk(FieldEditorPreferencePage.java:343)
at org.eclipse.jface.preference.PreferencePage.performApply(PreferencePage.java:432)
at org.eclipse.jface.preference.PreferencePage$2.widgetSelected(PreferencePage.java:281)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:248)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4169)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3758)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
at org.eclipse.jface.window.Window.open(Window.java:801)
at org.eclipse.ui.internal.dialogs.WorkbenchPreferenceDialog.open(WorkbenchPreferenceDialog.java:215)
at org.eclipse.ui.internal.handlers.ShowPreferencePageHandler.execute(ShowPreferencePageHandler.java:54)
at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:290)
at org.eclipse.core.commands.Command.executeWithChecks(Command.java:499)
at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
at org.eclipse.ui.internal.handlers.HandlerService.executeCommand(HandlerService.java:169)
at org.eclipse.ui.internal.handlers.SlaveHandlerService.executeCommand(SlaveHandlerService.java:241)
at org.eclipse.ui.menus.CommandContributionItem.handleWidgetSelection(CommandContributionItem.java:829)
at org.eclipse.ui.menus.CommandContributionItem.access$19(CommandContributionItem.java:815)
at org.eclipse.ui.menus.CommandContributionItem$5.handleEvent(CommandContributionItem.java:805)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4169)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3758)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2701)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2665)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2499)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:679)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:668)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at de.allianz.abs.konvertortool.product.Application.start(Application.java:20)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
at org.eclipse.equinox.launcher.Main.main(Main.java:1414)
Note the [L at the beginning of the first part of the class cast exception [Lorg.eclipse.swt.graphics.FontData. This means the value is an array of FontData so you need to do:
Font font = new Font(Display.getCurrent(),
(FontData []) newValue);
You should also make sure you call dispose on any fonts you create.
During runtime, the class loaded is not the same as the class the calling code was compiled against. Make sure your runtime libraries are the same as your build libraries and that you do not have multiple versions of API's in either your runtime or build.

Why is this code throwing a ClassCastException in netbeans while its runing fine in eclipse

//Runtime Exception
Runtime exception occurs when following code is called in netbeans. works fine in eclipse.
public List<Ticket> findOpenTickets() {
Session session = null;
try {
session = getSession();
Criteria criteria = session.createCriteria(getReferenceClass());
criteria.add(Restrictions.eq(Ticket.PROP_CLOSED, Boolean.FALSE));
List list = criteria.list();
return list;
} finally {
closeSession(session);
}
}
exception stack trace is
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Short
at org.apache.derby.client.net.NetStatementRequest.buildFDODTA(Unknown Source)
at org.apache.derby.client.net.NetStatementRequest.buildSQLDTAcommandData(Unknown Source)
at org.apache.derby.client.net.NetStatementRequest.writeOpenQuery(Unknown Source)
at org.apache.derby.client.net.NetPreparedStatement.writeOpenQuery_(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.writeOpenQuery(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.flowExecute(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.executeQueryX(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.executeQuery(Unknown Source)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1787)
at org.hibernate.loader.Loader.doQuery(Loader.java:674)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2213)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
at org.hibernate.loader.Loader.list(Loader.java:2099)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:94)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1569)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
at com.model.dao.TicketDAO.findOpenTickets(TicketDAO.java:154)
at com.util.TicketActiveDateSetterTask.run(TicketActiveDateSetterTask.java:29)
at com.main.Application.initDatabase(Application.java:160)
at com.main.Application.start(Application.java:91)
at com.main.Main.main(Main.java:12)
I am unable to solve this exception. Because everything seems to be fine, same code is running fine in eclipse but producing runtime exception.
check if your hibernate.dialect is proper or not?? It must be of your DB..

Categories