How to find where the java ClassCastException is happening - java

Just wondering if anyone can see why i am getting the exception "java.lang.ClassCastException" from the code below.
RISService, RisPortType are lib that i got from a WSDL file and then use wsimport to generate the .java files
I know what the exception means but i am just not sure how to track it down.
// Instantiate the wsimport generated SXML API Service client --
RISService risportService = new RISService();
RisPortType risportPort = risportService.getRisPort();
// Set the URL, user, and password on the JAX-WS client
String hostUrl = "https://10.1.1.1:8443/realtimeservice2/services/RISService";
((BindingProvider) risportPort).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, hostUrl);
((BindingProvider) risportPort).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, cucmDetails.getAxlUsername());
((BindingProvider) risportPort).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, cucmDetails.getAxlPassword());
// create and populate the selectCmDevice request
SelectCmDevice sxmlParams = new SelectCmDevice();
CmSelectionCriteria criteria = new CmSelectionCriteria();
long maxNum = 200;
long modelNum = 255;
ArrayOfSelectItem items = new ArrayOfSelectItem();
//create a select item criteria to retrieve devices with names matching "SEP123412341234"
SelectItem item = new SelectItem();
item.setItem("SEP123412341234");
items.getItem().add(item);
//Search on all nodes
criteria.setNodeName("Any");
//get back max 200 phones. 9+ can get upto 1000
criteria.setMaxReturnedDevices(maxNum);
//get back phones only
criteria.setDeviceClass("Phone");
//255 means get back ALL phone models
criteria.setModel(modelNum);
//get back only Registered phones
criteria.setStatus("Registered");
//return results in order of name
criteria.setSelectBy("Name");
//array of phones to get results back for
criteria.setSelectItems(items);
sxmlParams.setCmSelectionCriteria(criteria);
//make selectCmDevice request
SelectCmDeviceReturn selectResponse = risportPort.selectCmDevice("",criteria); << This is where i get the exception outline below
Exception in thread "AWT-EventQueue-0" javax.xml.ws.WebServiceException:
java.lang.ClassCastException: [C cannot be cast to java.lang.String
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.$Proxy40.selectCmDevice(Unknown Source)
at utils._9.APIRIS9.getPhoneIPadd(APIRIS9.java:66)
Thanks
Alexis

I bet your password is being returned as a char[] and jaxws is expecting a String.

in my case
Object port = service.getPort(qname, c);
WSBindingProvider bp = (WSBindingProvider) port;
// Manually set connection timeouts as we seem to hit them during IT testing
Map<String, Object> requestContext = bp.getRequestContext();
requestContext.put(BindingProviderProperties.REQUEST_TIMEOUT, env.getProperty("timeout"));
requestContext.put(BindingProviderProperties.CONNECT_TIMEOUT, env.getProperty("timeout"));
as you can see requestContext.put() takes a String and a object, you thought putting a String timeout would work, but NO, java ws is expecting a int..
this is a massive catch ya.

Related

No data found exception using oracle olapi

i started experimenting with oracle olap api 'olapi', but i'm having some issues while running their examples package.
when i run MakingQueriesExamples.java in source package i get this error:
oracle.olapi.data.cursor.NoDataAvailableException
at oracle.express.olapi.data.full.DefinitionManager.handleException(Unknown Source)
at oracle.express.olapi.data.full.DefinitionManager.createCursorManagerInterfaces(Unknown Source)
at oracle.express.olapi.data.full.DefinitionManager.createCursorManagers(Unknown Source)
at oracle.olapi.data.source.DataProvider.createCursorManagers(Unknown Source)
at oracle.olapi.data.source.DataProvider.createCursorManagers(Unknown Source)
at oracle.olapi.data.source.DataProvider.createCursorManagers(Unknown Source)
at oracle.olapi.data.source.DataProvider.createCursorManagers(Unknown Source)
at oracle.olapi.data.source.DataProvider.createCursorManager(Unknown Source)
at olap.Context11g._displayResult(Context11g.java:650)
at olap.Context11g.displayResult(Context11g.java:631)
at olap.source.MakingQueriesExamples.controllingMatchingWithAlias(MakingQueriesExamples.java:114)
at olap.source.MakingQueriesExamples.run(MakingQueriesExamples.java:40)
at olap.BaseExample11g.execute(BaseExample11g.java:54)
at olap.BaseExample11g.execute(BaseExample11g.java:74)
at olap.source.MakingQueriesExamples.main(MakingQueriesExamples.java:478)
the part that's causing the error is in here (last line) (MakingQueriesExamples):
println("\nControlling Input-to-Source Matching With the alias Method");
MdmMeasure mdmUnits = getMdmMeasure("UNITS");
// Get the Source objects for the measure and for the default hierarchies
// of the dimensions.
NumberSource units = (NumberSource) mdmUnits.getSource();
StringSource prodHier = (StringSource)
getMdmPrimaryDimension("PRODUCT").getDefaultHierarchy().getSource();
StringSource custHier = (StringSource)
getMdmPrimaryDimension("CUSTOMER").getDefaultHierarchy().getSource();
StringSource chanHier = (StringSource)
getMdmPrimaryDimension("CHANNEL").getDefaultHierarchy().getSource();
StringSource timeHier = (StringSource)
getMdmPrimaryDimension("TIME").getDefaultHierarchy().getSource();
// Select single values for the hierarchies.
//Source prodSel = prodHier.selectValue("PRODUCT_PRIMARY::ITEM::ENVY ABM");
Source prodSel = prodHier.selectValue("PRIMARY::ITEM::ENVY ABM");
//Source custSel = custHier.selectValue("SHIPMENTS::SHIP_TO::BUSN WRLD SJ");
Source custSel = custHier.selectValue("SHIPMENTS::SHIP_TO::BUSN WRLD SJ");
//Source timeSel = timeHier.selectValue("CALENDAR_YEAR::MONTH::2001.01");
Source timeSel = timeHier.selectValue("CALENDAR::MONTH::2001.01");
// Produce a Source that specifies the units values for the selected
// dimension values.
Source unitsSel = units.join(timeSel).join(custSel).join(prodSel);
// Create aliases for the Channel dimension hierarchy.
Source chanAlias1 = chanHier.alias();
Source chanAlias2 = chanHier.alias();
// Join the aliases to the Source representing the units values specified
// by the selected dimension elements, using the value method to make the
// alias an input.
NumberSource unitsSel1 = (NumberSource) unitsSel.join(chanAlias1.value());
NumberSource unitsSel2 = (NumberSource) unitsSel.join(chanAlias2.value());
// chanAlias2 is the first output of result, so its values are the row
// (slower varying) values; chanAlias1 is the second output of result
// so its values are the column (faster varying) values.
Source result = unitsSel1.gt(unitsSel2)
.join(chanAlias1) // Output 2, column
.join(chanAlias2); // Output 1, row
getContext().commit();
getContext().displayResult(result);
and in here (first line)(context11g.java):
CursorManager cursorManager =
dp.createCursorManager(source);
Cursor cursor = cursorManager.createCursor();
cpw.printCursor(cursor, displayLocVal);
// Close the CursorManager.
cursorManager.close();
i'm using oracle database 11.2.0.1.0 with OLAP option enabled and oracle analytical workplace manager 11.2.0.4B
i've started by installing the 'global' schema as instructed here:
https://www.oracle.com/technetwork/database/options/olap/global-11g-readme-082667.html
i verified everything in AWM (cubes, dimensions and mesures), and the data in sqldevelopper.
i've noticed that some of the hierarchies' names have changed so i updated them on the java code
any help would be appreciated !
thanks in advance

IndexNotFoundException[no such index]

I was running my first elasticsearch test case, I am using Java as the solution perspective to do elasticsearch experiment. it works perfectly fine in eclipse Debug Mode,
the debug mode result:
{postDate=2016-01-31T10:32:58.952Z, title=Posting, content=today's weather is hot, tags=[hashtag]}
But when I try this on in normal Run application mode, I am getting the following exception and I have no idea at all. Please guide me.
The following exception:
8253 [main] INFO org.elasticsearch.node - [Marc Spector] started
8257 [elasticsearch[Marc Spector][clusterService#updateTask][T#1]] DEBUG org.elasticsearch.index.store - [Marc Spector] [facebook] using index.store.throttle.type [none], with index.store.throttle.max_bytes_per_sec [0b]
8273 [elasticsearch[Marc Spector][search][T#4]] DEBUG org.elasticsearch.action.search.type - [Marc Spector] All shards failed for phase: [query]
RemoteTransportException[[Marc Spector][127.0.0.1:9300][indices:data/read/search[phase/query]]]; nested: IndexNotFoundException[no such index];
Caused by: [facebook] IndexNotFoundException[no such index]
at org.elasticsearch.indices.IndicesService.indexServiceSafe(IndicesService.java:310)
at org.elasticsearch.search.SearchService.createContext(SearchService.java:635)
at org.elasticsearch.search.SearchService.createAndPutContext(SearchService.java:617)
at org.elasticsearch.search.SearchService.executeQueryPhase(SearchService.java:368)
at org.elasticsearch.search.action.SearchServiceTransportAction$SearchQueryTransportHandler.messageReceived(SearchServiceTransportAction.java:368)
at org.elasticsearch.search.action.SearchServiceTransportAction$SearchQueryTransportHandler.messageReceived(SearchServiceTransportAction.java:365)
at org.elasticsearch.transport.TransportService$4.doRun(TransportService.java:350)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception in thread "main" Failed to execute phase [query], all shards failed
at org.elasticsearch.action.search.type.TransportSearchTypeAction$BaseAsyncAction.onFirstPhaseResult(TransportSearchTypeAction.java:228)
at org.elasticsearch.action.search.type.TransportSearchTypeAction$BaseAsyncAction$1.onFailure(TransportSearchTypeAction.java:174)
at org.elasticsearch.action.ActionListenerResponseHandler.handleException(ActionListenerResponseHandler.java:46)
at org.elasticsearch.transport.TransportService$DirectResponseChannel.processException(TransportService.java:821)
at org.elasticsearch.transport.TransportService$DirectResponseChannel.sendResponse(TransportService.java:799)
at org.elasticsearch.transport.TransportService$4.onFailure(TransportService.java:361)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:42)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
8278 [elasticsearch[Marc Spector][clusterService#updateTask][T#1]] DEBUG org.elasticsearch.index.mapper - [Marc Spector] [facebook] using dynamic[true]
The I think showing source code can be more clear to the issue
Source:
Node node = nodeBuilder().clusterName("testing2").node();
Client client = node.client();
SearchResponse response = client.prepareSearch("facebook")
.setTypes("Lance")
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(QueryBuilders.matchPhrasePrefixQuery("title", "Pos"))
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
SearchHit[] searchResponse = response.getHits().getHits();
for(SearchHit hit : searchResponse){
System.out.println(hit.getSource());
}
Before querying your facebook index, you need to create it first:
Settings indexSettings = ImmutableSettings.settingsBuilder()
.put("number_of_shards", 5)
.put("number_of_replicas", 1)
.build();
CreateIndexRequest indexRequest = new CreateIndexRequest("facebook", indexSettings);
client.admin().indices().create(indexRequest).actionGet();
And if you expect to find some results, you need to index your data also:
IndexResponse response = client.prepareIndex("facebook", "Lance", "1")
.setSource(jsonBuilder()
.startObject()
.field("title", "Posting")
.field("postDate", new Date())
.field("content", "today's weather is hot")
.field("tags", Lists.newArrayList("hashtag"))
.endObject()
)
.execute()
.actionGet();
Then you can search on your index.

Octave not able to evaluate script due to failure in loading scalar constant

I have a project where I need to make several computations using Octave. I communciate with Octave using the javaoctave bridge. Below is simplified example code to show what I am doing.
// One of the fields of my class that evaluates equations. This class is provided by teh bridge.
private OctaveEngine scriptEngine;
// The script contains the equation, e.g.: Ampere = PowerConsumption (Lights, Dryer, Dishwasher, Laptop, Smartphone);
private String script;
public synchronized void evaluate() {
// Variable is a class implementing Cloneable and harbouring a unit as well as its unit and a few utility functions.
LinkedHashSet<Variable> dependentVariables;
String evaluationErrors;
Preconditions.checkState(scriptEngine != null);
try {
engineErrors.reset();
scriptEngine.setErrorWriter(engineErrors);
initParameters();
scriptEngine.eval(this.script);
} catch (Exception exception) {
LOGGER.log(Level.SEVERE, "Error while evaluating script " + this.script, exception); //$NON-NLS-1$
}
// The mapping stores the variables and the interface objects changing or reading their values.
dependentVariables = mapping.getDependentVariables();
for (Variable variable : dependentVariables) {
try {
OctaveDouble result = scriptEngine.get(OctaveDouble.class, variable.getName());
variable.setValue(result.get(1));
} catch (Exception exception) {
LOGGER.log(Level.SEVERE, "Error while retrieving variable " + variable.getName(), exception); //$NON-NLS-1$
}
}
evaluationErrors = engineErrors.toString();
if (evaluationErrors.length() > 0) {
LOGGER.log(Level.WARNING, "Error while evaluating equation :" + evaluationErrors); //$NON-NLS-1$
}
}
private void initParameters() {
for (Variable variable : lockedMapping.getIndependentVariables()) {
Double numericValue = Double.valueOf(variable.getValue().toString());
if (isNegative(numericValue)) {
numericValue *= -1d;
}
scriptEngine.put(variable.getName(), Octave.scalar(numericValue));
}
}
private static boolean isNegative(double _double) {
return Double.doubleToRawLongBits(_double) < 0;
}
What I was getting as error message was that:
WARNING: Error while evaluating equation :error: load: failed to load scalar constant
error: load: trouble reading ascii file '-'
error: load: reading file -
Googling a bit I found that negative values (or large inputs) can cause this problem. However, it was deemed to be solved. I don't have large inputs and I tried to make sure my values are positive (which all were even by testing using a syso!
I did a more in-depth search for the root cause and stumbled upon it. It seems that in the OcaveExec class, line 157 in the getFromFuture method where it calles future.get(), an ExecutionException is thrown. Below is the immediate stacktrace:
java.util.concurrent.ExecutionException: dk.ange.octave.exception.OctaveIOException: IOException during close
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at dk.ange.octave.exec.OctaveExec.getFromFuture(OctaveExec.java:157)
at dk.ange.octave.exec.OctaveExec.eval(OctaveExec.java:142)
at dk.ange.octave.io.OctaveIO.set(OctaveIO.java:56)
at dk.ange.octave.OctaveEngine.put(OctaveEngine.java:141)
at [redacted].OctaveEquation.initParameters(OctaveEquation.java:109)
at [redacted].OctaveEquation.evaluate(OctaveEquation.java:72)
at [redacted].LinearEquationSystem.inputChanged(LinearEquationSystem.java:105)
at [redacted].variable.NumericalVariable.setValue(NumericalVariable.java:127)
at [redacted].widget.ValueWidget.actionDrop(ValueWidget.java:88)
at [redacted].TangibleObjectManager.dropObject(TangibleObjectManager.java:207)
at [redacted].adapter.TuioAdapter.addTangibleObject(TuioAdapter.java:318)
at [redacted].adapter.TuioAdapter.addTuioObject(TuioAdapter.java:295)
at TUIO.TuioClient.acceptMessage(TuioClient.java:339)
at com.illposed.osc.utility.OSCPacketDispatcher.dispatchMessage(OSCPacketDispatcher.java:73)
at com.illposed.osc.utility.OSCPacketDispatcher.dispatchPacket(OSCPacketDispatcher.java:49)
at com.illposed.osc.utility.OSCPacketDispatcher.dispatchBundle(OSCPacketDispatcher.java:56)
at com.illposed.osc.utility.OSCPacketDispatcher.dispatchPacket(OSCPacketDispatcher.java:40)
at com.illposed.osc.OSCPortIn.run(OSCPortIn.java:65)
at java.lang.Thread.run(Unknown Source)
Caused by: dk.ange.octave.exception.OctaveIOException: IOException during close
at dk.ange.octave.exec.OctaveReaderCallable.call(OctaveReaderCallable.java:65)
at dk.ange.octave.exec.OctaveReaderCallable.call(OctaveReaderCallable.java:1)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
... 1 more
Caused by: java.io.IOException: Pipe to octave-process broken
at dk.ange.octave.exec.OctaveExecuteReader.read(OctaveExecuteReader.java:68)
at java.io.Reader.read(Unknown Source)
at dk.ange.octave.exec.OctaveExecuteReader.close(OctaveExecuteReader.java:96)
at dk.ange.octave.exec.OctaveReaderCallable.call(OctaveReaderCallable.java:61)
... 5 more
java.util.concurrent.ExecutionException: dk.ange.octave.exception.OctaveIOException: IOException during close
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at dk.ange.octave.exec.OctaveExec.getFromFuture(OctaveExec.java:157)
at dk.ange.octave.exec.OctaveExec.eval(OctaveExec.java:142)
at dk.ange.octave.io.OctaveIO.set(OctaveIO.java:56)
at dk.ange.octave.OctaveEngine.put(OctaveEngine.java:141)
at [redacted].OctaveEquation.initParameters(OctaveEquation.java:109)
at [redacted].OctaveEquation.evaluate(OctaveEquation.java:72)
at [redacted].LinearEquationSystem.inputChanged(LinearEquationSystem.java:105)
at [redacted].variable.NumericalVariable.setValue(NumericalVariable.java:127)
at [redacted].widget.ValueWidget.actionDrop(ValueWidget.java:88)
at [redacted].TangibleObjectManager.dropObject(TangibleObjectManager.java:207)
at [redacted].adapter.TuioAdapter.addTangibleObject(TuioAdapter.java:318)
at [redacted].adapter.TuioAdapter.addTuioObject(TuioAdapter.java:295)
at TUIO.TuioClient.acceptMessage(TuioClient.java:339)
at com.illposed.osc.utility.OSCPacketDispatcher.dispatchMessage(OSCPacketDispatcher.java:73)
at com.illposed.osc.utility.OSCPacketDispatcher.dispatchPacket(OSCPacketDispatcher.java:49)
at com.illposed.osc.utility.OSCPacketDispatcher.dispatchBundle(OSCPacketDispatcher.java:56)
at com.illposed.osc.utility.OSCPacketDispatcher.dispatchPacket(OSCPacketDispatcher.java:40)
at com.illposed.osc.OSCPortIn.run(OSCPortIn.java:65)
at java.lang.Thread.run(Unknown Source)
Caused by: dk.ange.octave.exception.OctaveIOException: IOException during close
at dk.ange.octave.exec.OctaveReaderCallable.call(OctaveReaderCallable.java:65)
at dk.ange.octave.exec.OctaveReaderCallable.call(OctaveReaderCallable.java:1)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
... 1 more
Caused by: java.io.IOException: Pipe to octave-process broken
at dk.ange.octave.exec.OctaveExecuteReader.read(OctaveExecuteReader.java:68)
at java.io.Reader.read(Unknown Source)
at dk.ange.octave.exec.OctaveExecuteReader.close(OctaveExecuteReader.java:96)
at dk.ange.octave.exec.OctaveReaderCallable.call(OctaveReaderCallable.java:61)
... 5 more
I am working on a Windows 7 machine, have the path to the Octave bin on my classpath and not sure what I am doing wrong. I assume something goes wrong during IO but I can't seem to put my finger on it.
To be sure all my inputs are known, below are my *.m filed holding both scripts. All my inputs are positive and range from 0 to 2200 (as doubles).
function Load = CircuitLoad(Breaker, Lights, Dryer, Dishwasher, Laptop, Smartphone)
Load = Breaker / ((Lights + Dryer + Dishwasher + Laptop + Smartphone) / 230);
And the second one:
function Ampere = PowerConsumption(Lights, Dryer, Dishwasher, Laptop, Smartphone)
Ampere = (Lights + Dryer + Dishwasher + Laptop + Smartphone) / 230;

NullPointerException when accessing 2D array

First, here is my function "setProduct" :
public void setProduct(String code, int qty,double price,int nbrProduct){
System.out.println("Code = "+code);
System.out.println("qty = "+qty);
System.out.println("price = "+price);
System.out.println("nbrProduct = "+nbrProduct);
this.Produit[nbrProduct][0] = code;
this.Produit[nbrProduct][1] = Integer.toString(qty);
this.Produit[nbrProduct][2] = price+" €";
And now where I call :
Commande_Final Commande = new Commande_Final();
Commande = Cmd;
String name = Commande.getName();
double prixUnit = Function.GetMagPrice(radar,Qtyradar)/Qtyradar;
System.out.println("j'affiche le radar : "+name);
System.out.println("j'affiche le Qtyradar : "+Qtyradar);
System.out.println("j'affiche le prix du radar : "+prixUnit+" €");
System.out.println("nbr de produit = "+nbr_de_Produit);
Commande.setProduit(name,Qtyradar,prixUnit,nbr_de_Produit);
My problem :
I get an error when I do in "setProduct" => this.Produit[nbrProduct][0] = code;
The error says "java.lang.NullPointerException", I guess its trying to put an empty value in "this.Produit[nbrProduct][0]" but the thing is when I do the "System.out.println("Code = "+code);" its show me the correct code and the same for all others attributs :/
EDIT :
Here is how I create my Produit attribut :
public String[][] Produit = new String[99][3];
EDIT 2 :
stack trace :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Commande_Final.setProduit(Commande_Final.java:33)
at ZDialogInfo.Confirmer(ZDialogInfo.java:449)
at ZDialogV2$29.actionPerformed(ZDialogV2.java:1037)
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)
The code (sorry I leave in french, then you see the real name I use):
public void Confirmer(boolean LoginCheck,String Nom,ZDialogInfo zInfo,final String Langue, Commande_Final Cmd) throws IOException{
Commande_Final Commande = Cmd;
...
if (Qtyradar > 0){
/*
* PROBLEME ICI
*
* */
String name = Commande.showName();
double prixUnit = Function.GetMagPrice(radar,Qtyradar)/Qtyradar;
System.out.println("j'affiche le radar : "+name);
System.out.println("j'affiche le Qtyradar : "+Qtyradar);
System.out.println("j'affiche le prix du radar : "+prixUnit+" €");
System.out.println("nbr de produit = "+nbr_de_Produit);
/*ZDialogInfo.Confirmer(ZDialogInfo.java:449) => */
Commande.setProduit(name,Qtyradar,prixUnit,nbr_de_Produit);
nbr_de_Produit++;
System.out.println("nbr de produit = "+nbr_de_Produit);
JP_CNom.add(JL_CRadar);
JP_CNom.add(JL_CQtyRadar);
JP_CNom.add(JL_CPrixRadar);
if (RnbrItem >= 1) JP_CNom.add(RCompo1);
if (RnbrItem >= 2) JP_CNom.add(RCompo2);
if (RnbrItem >= 3) JP_CNom.add(RCompo3);
}
My public class Commande_Final
public class Commande_Final {
private String[][] Produit = new String[MAX_Produit][3];
/*
*
* [Nbr de Produit][0] = Code_Item
* [Nbr de Produit][1] = Qty_Cmdé
* [Nbr de Produit][2] = Prix_Unitaire
*
* */
public void setProduit(String code, int qty,double prix,int nbrProduit){
System.out.println(" ------------------- Dans setProduit ---------------------- ");
System.out.println("Code = "+code);
System.out.println("qty = "+qty);
System.out.println("prix = "+prix);
System.out.println("nbrProduit = "+nbrProduit);
/*at Commande_Final.setProduit(Commande_Final.java:33) =>*/ this.Produit[nbrProduit][0] = code;
this.Produit[nbrProduit][1] = Integer.toString(qty);
this.Produit[nbrProduit][2] = prix+"";
}
Most probably you haven't set up the array correctly.
A simplest example:
Foo[] foo = new Foo[10];
it is just making an array with 10 reference to Foo, however there is no actual Foo object those reference is pointing to. Hence it will cause NPE when you are trying to access foo[0].bar()
Similar,
Product[][] product = new Product[10][];
is going to give u an array of 10 reference pointing to Product[]. However there is no actual Product array object created. Therefore similar to the above example, you will get NPE if you do product[1][0], because product[1] is point to null, NPE is thrown because you want to access [0] of that null Product[] reference. You need to instantiate them explicitly.
Update:
With the extra code that OP quoted, I have tried to run that and there is no NPE from that piece of code.
It is most probably that, you have reassigned your produit (I would strongly recommend you follow Java's common naming convention) to null, or assigned produit[n] to null in some other code.
I would suggest a quick check on which one is null:
Add before your assignment:
System.out.println("produit null ? " + (produit == null));
System.out.println("produit[n] null ? " + (produit[nbrProduit] == null));
it should tell you which one is null, and give you hints where you may have incorrect updated the reference.
Problem
According to your stack trace, NPE is caused by this line:
this.Produit[nbrProduct][0] = code;
Apparently, you found out via console output that what is null here is this.Produit.
Possible Cause
Since you said you initialized Produit with the following line:
private String[][] Produit = new String[99][3];
then your NPE should not happen, unless you have reset the reference to null somewhere via some code like:
Commande.Produit = null;
Finding write accesses
If you're using Eclipse, there is a way to find every write access to your attribute:
click on your attribute Produit in your Commande_Final class, so that it is highlighted
go to Search > Write Access > Project
check if there is any other write access than your initialization
My guess is that this.Produit[nbrProduct] is null.
It can be initialized: this.Produit[nbrProduct] = new String[someSize];
Assigning null never causes a NPE, the issue must be your array has been not initialized.
The array is initialized when the object is created, so my guess is that array is re-assigned before the setProduct method is called. Check if this.Produit[nbrProduct] is not null when setProduct is called.
PS: Please, use Java conventions: method, attribute and variable names start with lowcase, class/interface names start with uppercase. In general try to use CamelCase (except constants, that should be LIKE_THIS_EXAMPLE)

Java - Unknown attribute MS-CHAP-Challenge

I am following this little example in java, to test JRadius client.
But I keep getting this error:
Exception in thread "main" net.sf.jradius.exception.UnknownAttributeException: Unknown attribute MS-CHAP-Challenge
at net.sf.jradius.packet.attribute.AttributeFactory.newAttribute(Unknown Source)
at net.sf.jradius.client.auth.MSCHAPv2Authenticator.processRequest(Unknown Source)
at net.sf.jradius.client.RadiusClient.authenticate(Unknown Source)
at lu.restena.zimbra.RestenaAuthenticator.main(RestenaAuthenticator.java:94)
I have added all jars already and imports too.
My code:
InetAddress remoteInetAddress = InetAddress.getByName(RADIUSname);
RadiusClient radiusClient;
radiusClient = new RadiusClient(
remoteInetAddress, // InetAddress - Address of remote RADIUS Server
sharedSecret); // String - Shared Secret for remote RADIUS Server
AttributeList attributeList;
attributeList = new AttributeList();
attributeList.add(new Attr_UserName(username));
RadiusAuthenticator auth = RadiusClient.getAuthProtocol("mschapv2");
RadiusPacket request;
request = new AccessRequest(radiusClient, attributeList);
request.addAttribute(new Attr_UserPassword(password));
RadiusPacket reply = radiusClient.authenticate((AccessRequest) request, auth, 5);
The error is on:
RadiusPacket reply = radiusClient.authenticate((AccessRequest) request, auth, 5);
Anyone has any idea why? (I am a newbie in JRadius) (MSCHAPv2Authenticator.java)
Before using the JRadius library, a JRadius dictionary should be loaded as below.
AttributeFactory.loadAttributeDictionary("net.jradius.dictionary.AttributeDictionaryImpl");
Also, ensure you have added JRadius Dictionary (jradius-dictionary-.jar) to you class path.

Categories