W3CHttpResponseCodec error while Selenium Driver runs over VPN in Java - java

when I run my code without VPN my code works but when I connect VPN connection I get many errors such as:
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:277)
at RequestWithSelenium.checkBody(RequestWithSelenium.java:71)
at Main$3.run(Main.java:70)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
My code explanation is simply that it tries to fetch sites which has includes error messages in body tag.
public void checkBody() {
for(String siteFinder: webSites) {
System.out.println("Selenium has visited " + siteFinder + " succesfully.");
driver.get(siteFinder);
bodyCheck = driver.findElement(By.tagName("body")).getText();
for(String errFinder: errorMsgs) {
if(bodyCheck.contains(errFinder)) {
errorSites.add(siteFinder);
}
}
}
driver.close();
if(errorSites.isEmpty()) {
System.out.println("There is no down site has found.");
} else {
System.out.println("Down site(s) list has shown below.");
int listMeter = 1;
for(String downSites: errorSites) {
System.out.println(listMeter + "th site: " + downSites);
listMeter++;
}
}
}
How can I fix this issue? Thanks.

Related

Failed to access the WSDL

Hello I am trying setting up a simple WSDL program in Java but I get the following error, any advices? I am fairly new at this, and this program is my first one of sorts.
Thank you,
package de.vs.webServices.clientSide;
import java.net.URL;
import java.util.Scanner;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import de.vs.webServices.serverSide.ZeichenketteInt;
public class ZeichenketteClient {
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:9999/vs/Zeichenkette?wsdl");
QName qname = new QName("http://serverSide.webServices.vs.de/","ZeichenketteImplService");
Service service = Service.create(url, qname);
ZeichenketteInt zeichenketteInt = service.getPort(ZeichenketteInt.class);
Scanner sc = new Scanner(System.in);
int nr=0;
do {
System.out.println("Waehlen Sie die Nummer eines Befehls oder 0 um das Programm zu beenden: ");
System.out.println("1. Zeichen Doppeln");
System.out.println("2. Zeichenkette Verdoppeln");
System.out.println("3. ZeichenketteSpiegeln");
System.out.println("4. ZeichenketteLange");
nr = sc.nextInt();
String zeichenkette = null;
switch (nr) {
case 1:
System.out
.println("Schreiben Sie die gewunschte Zeichenkette: ");
zeichenkette = sc.next();
System.out.println("Ergebnis: "
+ zeichenketteInt.zeichenDoppeln(zeichenkette));
break;
case 2:
System.out
.println("Schreiben Sie die gewunschte Zeichenkette: ");
zeichenkette = sc.next();
System.out.println("Ergebnis: "
+ zeichenketteInt.zeichenKetteVerdoppeln(zeichenkette));
break;
case 3:
System.out
.println("Schreiben Sie die gewunschte Zeichenkette: ");
zeichenkette = sc.next();
System.out.println("Ergebnis: "
+ zeichenketteInt.zeichenKetteSpiegeln(zeichenkette));
break;
case 4:
System.out
.println("Schreiben Sie die gewunschte Zeichenkette: ");
zeichenkette = sc.next();
System.out.println("Ergebnis: "
+ zeichenketteInt.zeichenKetteLange(zeichenkette));
break;
}
} while (nr!=0);
sc.close();
}}
This is the error that I get:
Exception in thread "main" javax.xml.ws.WebServiceException: Failed to access the WSDL at: http://localhost:9999/vs/Zeichenkette?wsdl. It failed with:
Connection refused: connect.
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.tryWithMex(Unknown Source)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(Unknown Source)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(Unknown Source)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.parseWSDL(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(Unknown Source)
at javax.xml.ws.Service.<init>(Unknown Source)
at javax.xml.ws.Service.create(Unknown Source)
at de.vs.webServices.clientSide.ZeichenketteClient.main(ZeichenketteClient.java:19)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.createReader(Unknown Source)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.resolveWSDL(Unknown Source)
... 12 more
The part of the error that says: "refused: connect"
is telling you that the server (localhost in this case) rejected your connection request.
I would check that the URI: http://localhost:9999/vs/Zeichenkette?wsdl actually returns a WSDL document. Just open it in a web browser and see what you get back. If the browser can't open it, Java can't either. Once the browser will open it, Java should have no problem with it (though it occasionally happens that the browser reads it fine and permissions in Java stop you, this doesn't appear to be one of those cases).
Then I suggest looking to make certain that the server port is open (IPTables, AV, things like that can block it). Note that this is not likely your problem, since the error is reading the WSDL. I'm looking ahead to after the WSDL loads.

Error serializing element in ehcache

I get the following error, when puting an element in the ehcache. Does anyone have any idea why this error occures?
Thank you in advance.
This is put method:
#SuppressWarnings("unchecked")
#Override
public void putActivity(Activity activity) {
// put activity itself
Serializable activityKey = KEY_PREFIX_ACTIVITY + activity.getId();
final Element activityElement = new Element(activityKey, activity);
getCache().put(activityElement);
// add activity to the list of user
ArrayList<Activity> activities = null;
Serializable userKey = KEY_PREFIX_USER_ACTIVITIES + activity.getExecutingUserId();
Element userActivities = getCache().get(userKey);
if (userActivities == null) {
activities = new ArrayList<Activity>();
userActivities = new Element(userKey, activities);
} else {
activities = (ArrayList<Activity>) userActivities.getObjectValue();
}
activities.add(activity);
getCache().put(userActivities);
}
and here is the corresponding erorr:
Mrz 05, 2016 11:07:40 AM net.sf.ehcache.store.disk.DiskStorageFactory$DiskWriteTask call
Schwerwiegend: Disk Write of u-1 failed:
net.sf.ehcache.CacheException: Failed to serialize element due to ConcurrentModificationException. This is frequently the result of inappropriately sharing thread unsafe object (eg. ArrayList, HashMap, etc) between threads
at net.sf.ehcache.store.disk.DiskStorageFactory.serializeElement(DiskStorageFactory.java:405)
at net.sf.ehcache.store.disk.DiskStorageFactory.write(DiskStorageFactory.java:385)
at net.sf.ehcache.store.disk.DiskStorageFactory$DiskWriteTask.call(DiskStorageFactory.java:477)
at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1071)
at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1055)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.util.ConcurrentModificationException
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor33.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
at net.sf.ehcache.Element.writeObject(Element.java:875)
at sun.reflect.GeneratedMethodAccessor31.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at net.sf.ehcache.util.MemoryEfficientByteArrayOutputStream.serialize(MemoryEfficientByteArrayOutputStream.java:97)
at net.sf.ehcache.store.disk.DiskStorageFactory.serializeElement(DiskStorageFactory.java:403)
... 10 more
and here more details from ehcache source code:
private MemoryEfficientByteArrayOutputStream [More ...] serializeElement(Element element) throws IOException {
// A ConcurrentModificationException can occur because Java's serialization
// mechanism is not threadsafe and POJOs are seldom implemented in a threadsafe way.
// e.g. we are serializing an ArrayList field while another thread somewhere in the application is appending to it.
try {
return MemoryEfficientByteArrayOutputStream.serialize(element);
} catch (ConcurrentModificationException e) {
throw new CacheException("Failed to serialize element due to ConcurrentModificationException. " +
"This is frequently the result of inappropriately sharing thread unsafe object " +
"(eg. ArrayList, HashMap, etc) between threads", e);
}
}
You are updating an object while it's been serialized (ehcache try to save it to disk). You should store in a cache only an immutable object.
In your case, don't try to reuse the ArrayList, create a new one:
if (userActivities == null) {
activities = new ArrayList<Activity>();
userActivities = new Element(userKey, activities);
} else {
activities = new ArrayList<Activity>((List) userActivities.getObjectValue());
}
Instead of an ArrayList, you can instanciate a CopyOnWriteArrayList.

com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 403: Forbidden

I am getting following error while using the SharePoint web service:
com.sun.xml.internal.ws.client.ClientTransportException: The server
sent HTTP status code 403: Forbidden at
com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.checkStatusCode(Unknown
Source) at
com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.createResponsePacket(Unknown
Source) at
com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.process(Unknown
Source) at
com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.processRequest(Unknown
Source) at
com.sun.xml.internal.ws.transport.DeferredTransportPipe.processRequest(Unknown
Source) at com.sun.xml.internal.ws.api.pipe.Fiber.__doRun(Unknown
Source) at com.sun.xml.internal.ws.api.pipe.Fiber._doRun(Unknown
Source) at com.sun.xml.internal.ws.api.pipe.Fiber.doRun(Unknown
Source) at com.sun.xml.internal.ws.api.pipe.Fiber.runSync(Unknown
Source) at com.sun.xml.internal.ws.client.Stub.process(Unknown
Source) at
com.sun.xml.internal.ws.client.sei.SEIStub.doProcess(Unknown Source)
at
com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(Unknown
Source) at
com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(Unknown
Source) at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(Unknown
Source) at com.sun.proxy.$Proxy34.getListItems(Unknown Source) at
com.jw.sharepoint.examples.SharePointListExample.querySharePointFolder(SharePointListExample.java:67)
at
com.jw.sharepoint.examples.SharePointListExample.main(SharePointListExample.java:50)
I am trying to access SharePoint 2010 web service using the following code:
public void querySharePointFolder(ListsSoap ls) throws Exception {
try
{
disableCertificateValidation();
GetListItems.ViewFields viewFields = null;
GetListItems.QueryOptions msQueryOptions = new GetListItems.QueryOptions();
GetListItems.Query msQuery = new GetListItems.Query();
msQuery.getContent().add(createSharePointCAMLNode(query));
msQueryOptions.getContent().add(createSharePointCAMLNode(this.queryOptions));
GetListItemsResponse.GetListItemsResult result = ls.getListItems(
properties.getProperty("folder"), "", msQuery, viewFields, "",
msQueryOptions, "");
writeResult(result.getContent().get(0), System.out);
Element element = (Element)result.getContent().get(0);
NodeList nl = element.getElementsByTagName("z:row");
for(int i = 0; i < nl.getLength(); i++){
Node node = nl.item(i);
logger.debug("ID: " + node.getAttributes().getNamedItem("ows_ID").getNodeValue());
logger.debug("FileRef: " + node.getAttributes().getNamedItem("ows_FileRef").getNodeValue());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
But its showing the error at following line:
GetListItemsResponse.GetListItemsResult result = ls.getListItems(
properties.getProperty("folder"), "", msQuery, viewFields, "",
msQueryOptions, "");
Can you please help me out over this as after using different different approaches i am still getting the same issue 403: Forbidden.
I am using the same credential here through which i had created the folder over SharePoint. Do I need any other privileges for that credential to get the access.

Class.forName() throws ClassNotFoundException

So this is my first time posting, please be gentle :3
General overview:
My goal is to be able to give my program a XSD file, then the program generates a bean, generates a nice GUI using reflection on the bean, then I can enter appropriate values into the textfields and then the program updates the bean with the values and finally marshalls the bean into a nice XML.
It's coming along pretty good, but yesterday I stumbled over an error that I can't figure out..
StackTrace
java.lang.ClassNotFoundException: X.Y.Z.BEAN_FILE_WITHOUT_.JAVA
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at X.Y.Z.GenerateXMLService.generateBean(GenerateXMLService.java:101)
at X.Y.Z.view.Gui$1.handle(Gui.java:56)
at X.Y.Z.view.Gui$1.handle(Gui.java:1)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1800(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(Unknown Source)
at com.sun.glass.ui.win.WinApplication$4$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
generateBean
public Class generateBean(File xsd) {
String finalDir = System.getProperty("user.dir") + "/src/main/java";
String xsdDir = xsd.getParentFile().getAbsolutePath();
try {
Process p = Runtime.getRuntime().exec(
"cmd /c cd " + xsdDir + " && xjc -d " + finalDir
+ " -p PACKAGE_PATH_GOES_HERE " + xsd.getName().toString());
p.waitFor();
} catch (IOException | InterruptedException e) {
Gui.errorPopUp(e);
}
/**
* Get the newly created files and put them in an array
*/
File[] fList = new File[2];
fList = new File("DIRECTORY_PATH_GOES_HERE").listFiles();
/**
* Get the file that isn't Objectfactory.java ---> that's the bean
*/
for (File file : fList) {
if (!"ObjectFactory.java".equals(file.getName())) {
String beanName = file.getName();
String beanBinaryName = "PACKAGE_PATH_GOES_HERE"
+ beanName.substring(0, beanName.length() - 5);
Class beanClass = null;
try {
beanClass = Class.forName(beanBinaryName); //this is line 101
return beanClass;
} catch (ClassNotFoundException e) {
Gui.errorPopUp(e);
}
}
}
return null;
}
So I checked first if the beanBinaryName is correct, and I think it is. It has the following format:
com.foo.foo.some.more.foo.beanbag.bean
Then I started googling with the error message and stumbled accross this post:
Link to the blog
But to be honest I didn't really understand what he was trying to explain. The stacktrace looks similar, but I just started with java a few months ago and still consider myself a newbie. Do you have any advice what the error might be? Thank in advance!
EDIT / SOLUTION:
My first mistake was trying to use class.forName() on a .java file. This only works with compiled files, e.g. .class.
After I fixed that i was still getting error messages, but after playing around with the URLClassLoader it worked :D I renamed and refactored this method compared to the method at the top, so in this one we really only get the class, while in my first example I also generate the .java files. I now do this in a seperate method to keep things organized.
public Class getClassFromBean() {
File[] fList = new File[3];
fList = new File("foo/beanbag").listFiles();
Class beanClass = null;
for (File file : fList) {
String lastSix = file.getName().toString().substring(file.getName().length() - 6);
if (".class".equals(lastSix)) {
String beanBinaryName = "foo.beanbag."
+ file.getName().toString().substring(0, file.getName().toString().length() - 6);
try {
File root = new File(System.getProperty("user.dir") + "/src/main/java");
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI()
.toURL() });
beanClass = Class.forName(beanBinaryName, true, classLoader);
} catch (ClassNotFoundException | MalformedURLException e) {
Gui.errorPopUp(e);
}
return beanClass;
}
}
return beanClass;
}
Method Class.forName() works only for compiled classes i.e. for files with extension '.class'. You cannot just put '.java' file to your classpath.

removing last element in arraylist exception [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
At first there was an issue removing an element in an arraylist if it was the only one on the list but now there is an exception issue when deleting the last position of the arraylist. What is the best way to deal with this?
edit: Looking back, checking if it is the last element and putting in a dummy element to hold the only spot would work.
the code:
public void deleteCustomer(){
String id = null;
boolean c = false; //true if id is found
int remember = 0; //Remembers the deleted index
id = JOptionPane.showInputDialog(null,"input the if of whome you want to delete",
"input id", JOptionPane.PLAIN_MESSAGE);
int id2 = Integer.parseInt(id); //new int id.
for(int i = 0; i < customers.size(); i++){
if(id2 == customers.get(i).getID()){
if(customers.size() == 1){
System.out.println("test one person");
customers.get(i).setDate(null);
customers.get(i).setID(0);
customers.get(i).setName(null);
customers.get(i).setPeople(0);
}
else{
customers.remove(i);
}
c = true;
remember = i;
if(c == true)
break;
}
}
if(c == true){
int i1 = JOptionPane.showConfirmDialog(null,"the customer "
+ customers.get(remember).getName() + " has been deleted.",
"input people", JOptionPane.PLAIN_MESSAGE);
}
else{
int i1 = JOptionPane.showConfirmDialog(null,"the customer could not be found," +
" please check your id",
"input people", JOptionPane.PLAIN_MESSAGE);
}
}
the error
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at MainFrame.deleteCustomer(MainFrame.java:360)
at MainFrame$4.actionPerformed(MainFrame.java:170)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Don't remove elements from a collection while iterating over it with a for loop. Use an iterator instead which in most cases implements the remove method.
Iterator<Customer> it = customers.iterator();
while(it.hasNext()) {
if(it.next().getId() == id2) {
it.remove();
}
}
That's because you already removed one value, but the initial value in the condition (customer.size()) remains the same. So, the ACTUAL size of the list is 1, even though in the beginning was 2 or more.
What I would suggest is that instead of the for loop you use the iterator:
Iterator it = customers.iterator();
while (iterator.hasNext()) {
Customer customer= (Customer) it.next();
//do stuff with the customer
//remove the customer
it.remove();
}
there's a problem in your output.
After deleting the element with index i, you remember i.
int i1 = JOptionPane.showConfirmDialog(null,"the customer "
+ customers.get(remember).getName() + " has been deleted.",
"input people", JOptionPane.PLAIN_MESSAGE);
This piece of code, therefore, tries to access a deleted element from the list to get the name.
I would say you rewrite your method with the suggestions given by all previous answers. Something like this:
public void deleteCustomer(){
String id = null;
int remember = 0; //Remembers the deleted index
id = JOptionPane.showInputDialog(null,"input the id of whome you want to delete",
"input id", JOptionPane.PLAIN_MESSAGE);
int id2 = Integer.parseInt(id); //new int id.
Iterator<Customer> itr = customers.iterator();
while(itr.hasNext()){
Customer thisCustomer = itr.next();
if(id2 == thisCustomer.getID()){
customers.remove(thisCustomer);
break;
}
remember++;
}
if(remember < customers.size()){
JOptionPane.showConfirmDialog(null,"the customer has been deleted.",
"input people", JOptionPane.PLAIN_MESSAGE);
}
else{
JOptionPane.showConfirmDialog(null,"the customer could not be found," +
" please check your id",
"input people", JOptionPane.PLAIN_MESSAGE);
}
}

Categories

Resources