jGit push produces exception - exception

I am trying to use jGit in my java project. The version I am using is "2.0.0.201206130900-r" and my OS is Windows. everything worked fine until i tried to do a push:
public static void main(String[] args) {
File gitDir = new File("c:\\new-repo\\");
try {
String localPath = "c:\\new-repo\\";
Repository localRepo = new FileRepository(localPath + ".git");
localRepo.create();
Git git = new Git(localRepo);
git.add().addFilepattern("c:\\test.txt").call();
git.commit().setMessage("testcommit").call();
git.push().call();
localRepo.close();
} catch (IllegalStateException ise) {
System.out.println("The repository already exists!");
} catch (IOException ioe) {
System.out.println("Failed to create the repository!");
} catch (NoFilepatternException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GitAPIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
what i get is the following:
Exception in thread "main" java.lang.NoClassDefFoundError: com/jcraft/jsch/JSchException
at org.eclipse.jgit.transport.Transport.<clinit>(Transport.java:111)
at org.eclipse.jgit.api.PushCommand.call(PushCommand.java:141)
at Application.main(Application.java:76)
Caused by: java.lang.ClassNotFoundException: com.jcraft.jsch.JSchException
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
... 3 more
Can pls someone tell me what is wrong in my code?

It seems you are missing the jsch library which is needed for pushing over SSH. Add it to your classpath (add it to your pom if you're using Maven or add the jar to your classpath).

Related

Handling CompressorException in Java8 Streams

I have a static method for reading .bz2 files, it throws checked IOException and org.apache.commons.compress.compressors.CompressorException. The function signature is:
private static MyClass readFile(String fileName) throws IOException, CompressorException{
//…
}
Trying to use this method outright with Java8 streams gets compile time errors in Intellij;
unhandled exceptions: java.io.IOException, org.apache.commons.compress.compressors.CompressorException
So following advice from here, among others, I’ve tried the following but am stuck on how to handle the CompressorException object. Following it’s ctor I’ve tried as below but Intellij still complains the CompressorException is unhandled:
files.stream().forEach(i -> {
try{
readFile(i);
} catch (IOException e){
throw new RuntimeException(e);
} catch (Throwable ex){
throw new CompressorException("compressorException", ex);//error!!!
}
});
Thanks
As #JB Nizet mentioned in the comment, you cannot throw any Exception from the lambda function inside foreach function.
You need to replace your current implementation:
catch (Throwable ex){
throw new CompressorException("compressorException", ex);//error!!!
}
to either the following or not throw the RuntimeException at all.
catch (Throwable ex){
throw new RuntimeException("compressorException", ex);
}
The reason for the above behaviour is that the Stream.foreach() method has the following signature and doesn't throw any exception as part of the signature.
void forEachOrdered(Consumer<? super T> action)

unreported exception IOException; must be caught or declared to be thrown

I have a question , why does java keeps throwing that exception ! Is the problem with the stream ? because I handeled all IOExceptionS !
[[jio0yh.java:12: error: unreported exception IOException; must be
caught or declared to be thrown]]>>
That's the exception that I'm getting!
here is my code
import java.io.*;
public class jio0yh{
public static void main(String[]args){
FileInputStream OD=null;
try{
File f=new File("Binary.dat");
OD= new FileInputStream(f);
byte[]b=new byte[(int)f.length()];
OD.read(b);
for(int i=0;i<b.length;i++)
System.out.println(b[i]);
} catch(FileNotFoundException e){
System.out.println(e.getMessage());
} catch(IOException e){
System.out.println(e.getMessage());
OD.close();
}
}
}
The OD.close(); in your IOException catch block is also susceptible to throwing another IOException.
You should surround the final OD.close() in a finally block:
// ... Any previous try catch code
} finally {
if (OD != null) {
try {
OD.close();
} catch (IOException e) {
// ignore ... any significant errors should already have been
// reported via an IOException from the final flush.
}
}
}
Refer to the following for a more thorough explanation:
Java try/catch/finally best practices while acquiring/closing resources

Java Unit test for Exception

public Document query(String uri) throws IOException, IllegalArgumentException
{
final HttpGet httpget = new HttpGet(uri);
final HttpResponse response = httpclient.execute(httpget);
final HttpEntity entity = response.getEntity();
Document doc = null;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(entity.getContent());
}
catch (SAXException e)
{
LOGGER.error(e);
throw new IllegalArgumentException("parse error" + e);
}
catch (ParserConfigurationException e)
{
LOGGER.error(e);
throw new IllegalArgumentException("parameter factor is invalid: " + e);
}
catch (IllegalStateException e)
{
LOGGER.error(e);
throw new IllegalArgumentException("null entity contetents" + e);
}
return doc;
}
#Test(expected = IllegalArgumentException.class)
public void testQuery_ParseExceptionThrown() throws Exception
{
String uri ="some uri";
EasyMock.expect(httpClient.execute(EasyMock.isA(HttpGet.class))).andReturn(mockResponse);
EasyMock.expect(mockResponse.getEntity()).andReturn(mockEntity);
EasyMock.expect(mockEntity.getContent()).andReturn(new ByteArrayInputStream(REPSONSE_EXAMPLE.getBytes()));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
EasyMock.expect(builder.parse(EasyMock.isA(InputStream.class))).andThrow(
new IllegalArgumentException("expected"));
EasyMock.replay();
class.query(uri);
}
error:
java.lang.IllegalStateException: calling verify is not allowed in record state
at org.easymock.internal.MocksControl.verify(MocksControl.java:181)
at org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl.verify(EasyMockMethodInvocationControl.java:120)
at org.powermock.api.easymock.PowerMock.verify(PowerMock.java:1650)
at org.powermock.api.easymock.PowerMock.verifyAll(PowerMock.java:1586)
at com.amazon.ams.test.AbstractUnitTest.verifyMocks(AbstractUnitTest.java:78)
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 org.junit.internal.runners.MethodRoadie.runAfters(MethodRoadie.java:145)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:99)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:296)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:112)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:73)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:284)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:209)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:148)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:102)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I keep getting some errors like
java.lang.AssertionError: Expected exception: org.xml.sax.SAXException
java.lang.IllegalStateException: calling verify is not allowed in record state
There are 3 exceptions I need to write Junit test to get into the exception. Does anyone know how to use powermock or easymock class to write the unit test for it?
If you have a mock for the builder using easymock you can throw Exceptions instead of return values:
EasyMock.expect(builder.parse(myContent)).andThrow( myException);
Where myException is an Exception instance you want to throw (created by new MyException(...));
EDIT: example test code:
#Test
public void parseThrowsIllegalStateException(){
//... creating mock factory, builder and entity not shown
//create new Exception to be thrown
IllegalStateException expectedException = new IllegalStateException("expected");
EasyMock.expect(mockBuilder.parse(mockContent).andThrow(expectedException);
EasyMock.replay(...);
//exercise your system under test which tries to parse the entity's Content
//...
}
EDIT 2: now that you posted your actual test code I think the problem might be these lines:
EasyMock.expect(mockEntity.getContent()).andReturn(new ByteArrayInputStream(REPSONSE_EXAMPLE.getBytes()));
...
EasyMock.expect(builder.parse(new ByteArrayInputStream(malformed_XML.getBytes()))).andThrow(new SAXException("expected"));
I don't think ByteArrayInputStream overrides equals() so it is using Object.equals(). The ByteArrayInputStreams won't be equal so EasyMock will never throw the Exception
I would change the builder.parse() expectation to:
EasyMock.expect(builder.parse(EasyMock.isA(InputStream.class))).andThrow(new SAXException("expected"));
Which will throw when parse is called no matter what the inputStream is.
As a side note, your error message the mentioned "calling verify is not allowed in record state" but I don't see any calls to verify() or verifyAll() anywhere.

How to insert data into MySQL database by using the GWT, HTML and JDBC or Hibernate?

I am using the GWT(Google Web Tool-Kit) version 2.5.1. I am already done for develop sample application to display that username and password. But i am not identifying how to insert that values into MySQL database table by using JDBC of Hiberante. Any body know's that please send me complete code.
This is my mail-id:
subbareddyroyal#gmail.com
thanks & regards
Subbareddy.N
GWT is NOT a java application environment. It compiles to javascript. You must send your data to a java server running in a full JVM.
Here above i am posting the question.My self i a finding the answer to insert values into my sql database by using the jdbc, GWT,and HTML.
Here i am posting that what i am changing in my application.
you add the below insert in you impl class under the server folder in gwt application.
public void insert(String name) throws CommunicationsException {
try {
System.out.println("Before loading the driver class");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("after loading the driver ");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/gwt", "root", "root");
System.out.println("after creating the connection");
PreparedStatement ps = con
.prepareStatement("insert into gwt_user(userName)values(?)");
System.out.println("after loading the query");
ps.setString(1, name);
int i = ps.executeUpdate();
if (i < 0) {
return;
}
} catch (SQLException e) {
System.out.println(e);
}
}
after that you can add the below try catch block in ur greetserver(optional Name) method under the impl class.
try {
insert(name);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
then remaining all files are same.No need to change any file in your application

org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object?

I am using liferay 6.1 and created my custom portlet and in that I am using custom query which directly get the records from database with the following ....
public List<DashBoardBean> GetPieChartDataForCampaignbyOrganization(
ThemeDisplay pThemeDisplay) {
log.info("In GetPieChartDataForCampaignbyOrganization ");
Context CtxObj;
long pParentOrgId;
ResultSet advResultSet = null;
List<DashBoardBean> dashboardbeanObjList = new ArrayList<DashBoardBean>();
try {
CtxObj = new InitialContext();
DataSource DsObj = (DataSource) CtxObj
.lookup("java:comp/env/jdbc/Liferay");
Connection ConObj = DsObj.getConnection();
Statement sStmtObj = ConObj.createStatement();
advResultSet = sStmtObj
.executeQuery("MY CUSTOM QUERY WILL BE HERE");
while (advResultSet.next()) {
DashBoardBean dashboardbeanObj = new DashBoardBean();
dashboardbeanObj
.setsOrganizationName(advResultSet.getString(1));
dashboardbeanObj.setlOrganizationCount(advResultSet.getLong(2));
dashboardbeanObjList.add(dashboardbeanObj);
}
} catch (NamingException e) {
// TODO Auto-generated catch block
dashboardbeanObjList = null;
e.printStackTrace();
} catch (SQLException e) {
dashboardbeanObjList = null;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.info("Leave GetPieChartDataForCampaignbyOrganization ");
return dashboardbeanObjList;
}
Above is code snippet of one of my function... I have more then 5 function with the same structure... Just SQL query is different in function...
Now Problem is that I have to call more then 5 functions like this in page load...so when I use to reload the page frequently... It gives me error as following...
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:114)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at emenu.advertise.appbl.DashBoardCustomQuery.GetPieChartDataForCampaignStatus(DashBoardCustomQuery.java:112)
at emenu.advertise.appbl.DashBordBL.GetPieChartDataForCampaignStatus(DashBordBL.java:292)
at emenu.advertise.portlet.RestaurantPortlet.serveResource(RestaurantPortlet.java:402)
at com.liferay.portlet.FilterChainImpl.doFilter(FilterChainImpl.java:118)
at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:71)
at com.liferay.portal.kernel.servlet.PortletServlet.service(PortletServlet.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:72)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:73)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at com.liferay.portlet.InvokerPortletImpl.invoke(InvokerPortletImpl.java:531)
at com.liferay.portlet.InvokerPortletImpl.invokeResource(InvokerPortletImpl.java:626)
at com.liferay.portlet.InvokerPortletImpl.serveResource(InvokerPortletImpl.java:436)
at com.liferay.portal.action.LayoutAction.processPortletRequest(LayoutAction.java:1075)
at com.liferay.portal.action.LayoutAction.processLayout(LayoutAction.java:719)
at com.liferay.portal.action.LayoutAction.execute(LayoutAction.java:249)
at ............................
.......java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.util.NoSuchElementException: Timeout waiting for idle object
at org.apache.tomcat.dbcp.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1171)
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106)
... 131 more
09:24:11,163 INFO [http-bio-8080-exec-5][DashBoardCustomQuery:665] Leave GetHighestClickRestaurantName
09:24:11,163 INFO [http-bio-8080-exec-5][DashBoardCustomQuery:304] Leave GetLineChartDataForHighestClickedByRestaurant
09:24:11,164 INFO [http-bio-8080-exec-5][DashBordBL:166] Leave GetLineChartDataByRestaurant From DashBordBl
I know that I have done something wrong... But I don't know where... maybe it's because its SQL connection just lost from the server/// is it because I am not closing connection... Please help me... And correct me where am wrong... I had just given one example of my function the way I used to fetch data from other function...
i have just found the solution as i have never closed the connection object after execution of query.i have done as follows which works for me after try catch block...
finally {
try {
if(CtxObj!=null) {
CtxObj.close();
}
if(sStmtObj!=null){
sStmtObj.close();
}
if(ConObj!=null){
ConObj.close();
}
} catch (NamingException e) {
// TODO Auto-generated catch block
log.info(e);
} catch (SQLException e) {
// TODO Auto-generated catch block
log.info(e);
}
}