Exception in thread "main" java.lang.Error: - java

I have written the following code but its showing a compile time error that -
Transaction could not be resolved to a type
Even though I have imported org.hibernate.Transaction.
Could you please help. Following is my code:
package mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Mainclass {
public static void main(String[] args) {
//creating configuration object
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file
//creating seession factory object
SessionFactory factory=cfg.buildSessionFactory();
//creating session object
Session session=factory.openSession();
//creating transaction object
Transaction t= (Transaction)session.beginTransaction();
Employee e1=new Employee();
e1.setId(115);
e1.setFirstName("sonoo");
e1.setLastName("jaiswal");
session.persist(e1);//persisting the object
try {
t.commit();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.close();
System.out.println("successfully saved");
}
}

There is nothing wrong with the code as written. It should compile. There is a type called org.hibernate.Transaction - it is an interface.
So why might this not compile?
Maybe the above one isn't the version of the source code that you are compiling.
Maybe the compiler's build classpath is incorrect.
Maybe you are somehow mixing up the versions of the hibernate JAR files, and / or you are missing the JAR that contains >>that<< class.

Related

HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)

I have the following error and I am trying to figure out the reason. As far as I know, this is not caused by Hibernate but the way I manage/use the method calls (Transient entity instance, save, detach and then merge). I do not get why this problem happens. I would really appreciate your explanation.
Error:
HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: possible non-threadsafe access to session
FYI:
Java Version: 1.8
Hibernate version: https://hibernate.org/orm/releases/5.5/
package lk.mysite.demo.orm;
import lk.mysite.demo.orm.entity.Customer;
import lk.mysite.demo.orm.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class ContextDemo16 {
public static void main(String[] args) {
try (SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();) {
session.beginTransaction();
Customer customer = new Customer(5, "John", "New York");
session.save(customer);
session.detach(customer);
session.merge(customer);
// prompt an error
session.getTransaction().commit();
} catch (HibernateException e) {
e.printStackTrace();
}
}
}

Get an Exception when i using the Smack to build a java web project

I'm using smack API and openfire server to build a java IM software.And when i'm building the java code.the Console come up with this:
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.jivesoftware.smack.SmackConfiguration.getVersion(SmackConfiguration.java:96)
at org.jivesoftware.smack.ConnectionConfiguration.<clinit>(ConnectionConfiguration.java:38)
at test.main(test.java:12)
Caused by: java.lang.IllegalStateException: org.xmlpull.v1.XmlPullParserException: could not load any factory class (even small or full default implementation); nested exception is:
org.kxml2.io.XmlReader
at org.jivesoftware.smack.SmackInitialization.<clinit>(SmackInitialization.java:119)
... 3 more
Caused by: org.xmlpull.v1.XmlPullParserException: could not load any factory class (even small or full default implementation); nested exception is:
org.kxml2.io.XmlReader
at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java:225)
at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java:76)
at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:153)
at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:148)
at org.jivesoftware.smack.SmackInitialization.<clinit>(SmackInitialization.java:116)
... 3 more
My Code is like this:
import java.io.IOException;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
public class test {
public static void main(String args[])
{
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword("username", "password");
configBuilder.setResource("SomeResource");
configBuilder.setServiceName("172.29.41.168");
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
// Connect to the server
try {
connection.connect();
connection.login();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I already import the xmlpull_1_0_5.jar,how can i do to solve the problem?
To me it looks a bit like your dependencies might not be correctly setup.
So look less at your java code and more into the pom or other build files.

Java Dependency issue, not working for hibernate

Hello I am trying to follow this tutorial ::http://www.tutorialspoint.com/hibernate/hibernate_annotations.htm
my code in caseyou want to have a dig is here:
https://github.com/ArthurGibbs/Centaurus-
Im using restx framework.
I am trying to use hibernate to access a local database. however when i try compile my code i get a dependency error:
src/main/java/centaurus/service/UserDao.java:7: error: package org.hibernate does not exist
import org.hibernate.HibernateException;
but i have included it in my pom so i dont understand why I am getting the error.
this is my class where there error points to
package centaurus.service;
import centaurus.entity.GameUser;
import restx.factory.Component;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
#Component
public class UserDao {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new AnnotationConfiguration().
configure().
//addPackage("com.xyz") //add package if used.
addAnnotatedClass(GameUser.class).
buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
UserDao ME = new UserDao();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String email){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
GameUser employee = new GameUser();
employee.setEmail(email);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
public void saveId() {
addEmployee("bob");
}
}
new to hibernate, and not very experienced with maven. please help or let me know how to help you help me. thanks in advance
as I am using restx, it does not read the pom, it reads the md.restx.json file where i was missing the dependencies dependancies

IPOJO - The factory associated with the component type is invalid (not started or missing handlers)

I am trying to learn how to use Felix iPOJO API to create components dynamically.
I have a simple bundle with the following files:
1- HelloService.java (Contains a Service Interface).
/*
* #author zaid almahmoud
*
*/
package helloipojo.service;
public interface HelloService
{
public void sayHello();
}
2- Its implementation HelloServiceImpl.java:
package helloipojo;
import helloipojo.service.HelloService;
public class HelloServiceImpl implements HelloService{
#Override
public void sayHello() {
System.out.println("Hello iPojo!");
}
}
3- Activator.java :
package helloipojo;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
public void start(BundleContext context) throws Exception {
System.out.println("Bundle Started!");
}
public void stop(BundleContext context) throws Exception {
context = null;
System.out.println("Bundle Stopped!");
}
}
4- MANIFEST.MF :
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: HelloIPojo
Bundle-SymbolicName: HelloIPojo
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: helloipojo.Activator
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Import-Package: org.osgi.framework
In my application, I start Felix framework and deploy the following bundles:
iPOJO (core)
iPOJO Composite
iPOJO API
According to this source.
Next, I install my bundle, and instantiate the component. Below is my class:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.felix.framework.Felix;
import org.apache.felix.framework.util.FelixConstants;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.apache.felix.ipojo.ComponentInstance;
import org.apache.felix.ipojo.ConfigurationException;
import org.apache.felix.ipojo.MissingHandlerException;
import org.apache.felix.ipojo.UnacceptableConfiguration;
import org.apache.felix.ipojo.api.ComponentType;
import org.apache.felix.ipojo.api.PrimitiveComponentType;
import org.apache.felix.ipojo.api.Service;
public class HostApplication
{
private HostActivator m_activator = null;
private Felix m_felix = null;
public HostApplication()
{
// Create a configuration property map.
Map config = new HashMap();
config.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
// Create host activator;
m_activator = new HostActivator();
List list = new ArrayList();
list.add(m_activator);
config.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
try
{
// Now create an instance of the framework with
// our configuration properties.
m_felix = new Felix(config);
// Now start Felix instance.
m_felix.start();
}
catch (Exception ex)
{
System.err.println("Could not create framework: " + ex);
ex.printStackTrace();
}
// Register the application's context as an OSGi service!
BundleContext bundleContext1 = m_felix.getBundleContext();
System.out.println("6");
try {
//starting ipojo required bundles
Bundle coreBundle = bundleContext1.installBundle("file:C:\\Users\\zaid.almahmoud\\Dropbox\\EBTIC\\ADERE\\feasibility-codes\\ipojo\\ipojo-distribution-1.11.0\\bundle\\org.apache.felix.ipojo-1.6.2.jar");
coreBundle.start();
if(coreBundle.getState()== coreBundle.ACTIVE)
System.out.println("Core Bundle is Active!");
Bundle apiBundle = bundleContext1.installBundle("file:C:\\Users\\zaid.almahmoud\\Dropbox\\EBTIC\\ADERE\\feasibility-codes\\ipojo\\ipojo-distribution-1.11.0\\bundle\\org.apache.felix.ipojo.api-1.6.0.jar");
apiBundle.start();
if(apiBundle.getState()== apiBundle.ACTIVE)
System.out.println("API Bundle is Active!");
Bundle compositeBundle = bundleContext1.installBundle("file:C:\\Users\\zaid.almahmoud\\Dropbox\\EBTIC\\ADERE\\feasibility-codes\\ipojo\\ipojo-distribution-1.11.0\\bundle\\org.apache.felix.ipojo.composite-1.6.0.jar");
compositeBundle.start();
if(compositeBundle.getState()== compositeBundle.ACTIVE)
System.out.println("Composite Bundle is Active!");
//HERE INSTALLING AND STARTING MY BUNDLE!!
Bundle b = bundleContext1.installBundle("file:C:\\Users\\zaid.almahmoud\\Desktop\\plugins\\HelloIPojo_1.0.0.201401211340.jar");
b.start();
try {
ComponentType type = new PrimitiveComponentType()
.setBundleContext(b.getBundleContext())
.setComponentTypeName("hello.type")
.setClassName("helloipojo.HelloServiceImpl")
.setImmediate(true);
type.start();
ComponentInstance instance = type.createInstance();
}
catch (UnacceptableConfiguration
| MissingHandlerException | ConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Create the instance
System.out.println("done starting bundles!");
} catch (BundleException e) {
e.printStackTrace();
System.out.println("Not done!");
}
//shutdownApplication();
}
public Bundle[] getInstalledBundles()
{
// Use the system bundle activator to gain external
// access to the set of installed bundles.
return m_activator.getBundles();
}
public void shutdownApplication()
{
// Shut down the felix framework when stopping the
// host application.
try {
m_felix.stop();
} catch (BundleException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
m_felix.waitForStop(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When I run my application, it shows the following output (with the error at the end):
6
Core Bundle is Active!
API Bundle is Active!
Composite Bundle is Active!
Bundle Started!
Exception in thread "main" java.lang.IllegalStateException: The factory associated with the component type is invalid (not started or missing handlers)
at org.apache.felix.ipojo.api.ComponentType.ensureFactory(ComponentType.java:189)
at org.apache.felix.ipojo.api.ComponentType.ensureAndGetFactory(ComponentType.java:177)
at org.apache.felix.ipojo.api.ComponentType.createInstance(ComponentType.java:79)
at HostApplication.<init>(HostApplication.java:109)
at Embedder.main(Embedder.java:11)
Where did I go wrong? Thanks.
Update 1
I could see that I am missing 2 handlers. I knew that by adding the following two lines:
System.out.println(type.getFactory().getRequiredHandlers());
System.out.println(type.getFactory().getMissingHandlers());
The output of the above two lines is:
[org.apache.felix.ipojo:architecture, org.apache.felix.ipojo:callback]
[org.apache.felix.ipojo:architecture, org.apache.felix.ipojo:callback]
I also tried:
type.getFactory().createComponentInstance(new Properties());
then I got:
org.apache.felix.ipojo.MissingHandlerException: Missing handlers : org.apache.felix.ipojo:architecture org.apache.felix.ipojo:callback
I don't know why these handlers are missing. I tried to add them, but could not figure out the right syntax. Any help? Thanks.
Update 2
According to Clement in his answer, my bundle should import: org.apache.felix.ipojo and org.apache.felix.ipojo.architecture
I did that, and now I am getting the following error:
java.lang.ClassCastException: org.apache.felix.ipojo.HandlerManagerFactory cannot be cast to org.apache.felix.ipojo.HandlerFactory
I am getting the error at this line: type.start();
Please help. Thanks!
The issue comes from the asynchronous start of iPOJO. When you create your instance, not everything is available.
I’ve several question: Why are you using the iPOJO API to declare your type and instance ? Can’t you just use the annotations ? In that case it will just create everything smoothly.
If you really need / want to use the API, don’t create the instance like you do, but expose an instance declaration: http://felix.apache.org/documentation/subprojects/apache-felix-ipojo/apache-felix-ipojo-userguide/ipojo-advanced-topics/ipojo-factory-service.html#deleting-instances. The declaration waits until the factory is valid to create the instance.

Unhandled exception type IOEsxception using ApacheCommnonsIO's method

I am trying to use copyDirectory() method from ApacheCommnonsIO package.
My code is:
First Class
import java.io.*;
import org.apache.commons.io.FileUtils;
public class ClassN1{
public static methodThatUsesCPDIRMethod(){
String src = "/home/user/dir_src";
String dst = "/home/user/dir_dst";
try {
FileUtils.copyDirectory(new File(src), new File(dst));
} catch (IOException e){ }
}
Second class
public class ClassN2{
public ClassN2(){
ClassN1.methodThatUsesCPDIRMethod();
}
}
Main method
public class Main{
public static void main(String[] args){
ClassN2 obj = new ClassN2();
}
}
Is just an example, in code I haven't syntax errors, that can be there.
Problem: the ClassN1.methodThatUsesCPDIRMethod() in second's class constructor is highlighted with an error:
Unhandled exception type IOEsxception
I use VIM + Eclim plugin (Eclipse)
I did not check this, but it looks like the FileUtils are throwing this IOEsxception (interesting spelling!?) which your class don't catch. In this case you have to either add this exception to the method (the c'tor in your case) or you change the catch statement to catch the exception too.
try {
FileUtils.copyDirectory(new File(src), new File(dst));
} catch (Exception e){ //Please log at least a message here!!! }

Categories

Resources