I've got a class that allows me to authenticate with LDAP. When i run this code in a project with just one class (for testing reasons) i don't have problems and it returns a boolean value, as is expected, but when i run it in the project i'm working in, i got the following error:
java.lang.IncompatibleClassChangeError: Class org.apache.mina.filter.codec.ProtocolCodecFilter does not implement the requested interface org.apache.mina.core.filterchain.IoFilter
This is the method the allows me to authenticate:
public static void autenticarUsuario(String usuar, String password) throws LdapException, CursorException{
Dn user = Dn.EMPTY_DN;
try{
BasicConfigurator.configure();
LdapConnectionConfig config = new LdapConnectionConfig();
config.setLdapHost(SERVER_IP);
config.setLdapPort(PORT);
config.setName("uid=ldapsearch,ou=System,ou=Users,dc=fiec,dc=espol,dc=edu,dc=ec");
config.setCredentials(CREDENTIALS);
conn = new LdapNetworkConnection(config);
}catch(Exception e){
}
String s1 = usuar;
String s2 = password;
//System.out.println("Nombre: "+s1+" Contra: "+s2);
try {
conn.bind();
System.out.println(conn.isAuthenticated());
// Create the SearchRequest object
SearchRequest req = new SearchRequestImpl();
req.setScope( SearchScope.SUBTREE );
req.addAttributes( "*" );
req.setTimeLimit( 0 );
req.setBase( new Dn( "ou=Users,dc=fiec,dc=espol,dc=edu,dc=ec" ) );
req.setFilter( "(uid="+ s1 +")" );
// Process the request
SearchCursor searchCursor = conn.search( req );
while ( searchCursor.next() )
{
Response r = searchCursor.get();
if(r instanceof SearchResultEntry){
Entry re = ((SearchResultEntry) r).getEntry();
user = re.getDn();
}
}
conn.bind(user, s2);
//return(conn.isAuthenticated());
inLDAP = conn.isAuthenticated();
} catch (InvalidConnectionException ex) {
//System.out.println(ex);
}
catch (LdapException e) {
e.printStackTrace();
} catch (CursorException e) {
e.printStackTrace();
}
inLDAP = false;
}
The project i'm working in is a JAVAFX application, but this method is called in a class that doesn't extend from application (just java code to verify user credentials).
This is the stacktrace:
Exception in thread "pool-1-thread-1" java.lang.IncompatibleClassChangeError: Class org.apache.mina.filter.codec.ProtocolCodecFilter does not implement the requested interface org.apache.mina.core.filterchain.IoFilter
at org.apache.mina.core.filterchain.DefaultIoFilterChain.register(DefaultIoFilterChain.java:267)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.addLast(DefaultIoFilterChain.java:174)
at org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder.buildFilterChain(DefaultIoFilterChainBuilder.java:436)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.addNow(AbstractPollingIoProcessor.java:528)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.handleNewSessions(AbstractPollingIoProcessor.java:501)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$400(AbstractPollingIoProcessor.java:67)
at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:1116)
at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:51)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
These are the libraries i'm working:
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.Response;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchResultEntry;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.mina.*;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.exception.InvalidConnectionException;
import org.apache.log4j.BasicConfigurator;
I don't know why this is happening, i'll appreciate any help in advance
It is a version problem. Between Mina 1.0 and Mina 2.0, they moved the IoFilter interface (among other things) from org.apache.mina.filterchain to org.apache.mina.core.filterchain. I think you are trying to use code compiled for Mina 2.0 with the Mina 1.0 implementation.
Solution: examine your build and runtime classpaths and dependencies to figure out how this happened ... and fix the inconsistency.
Related
I am trying to use AWS S3AsyncClient to get/read file from Object Storage. My ultimate intention is to use this in my Vert.x project but before using with Vert.x I wanted to do get it working standalone. By following multiple forums I have written below code but it is giving error "software.amazon.awssdk.core.exception.SdkClientException: Credentials must not be null.". Even though I am providing credentials here, it says it's not getting them. Can anyone please help me here?
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
public class S3AsyncStreamOps {
public static void main(String[] args) {
AwsCredentialsProvider creds = StaticCredentialsProvider.create(AwsBasicCredentials.create("my_access_key", "my_secret_key"));
S3AsyncClient s3Client;
try {
s3Client = S3AsyncClient.builder().credentialsProvider(creds)
.region(Region.US_WEST_1)
.endpointOverride(new URI("https://someobjectstorage.server.com:9021"))
.build();
CompletableFuture<GetObjectResponse> futureGet = s3Client.getObject(
GetObjectRequest.builder()
.bucket("my_bucket_name")
.key("/somepath/anotherpath/myData.pdf")
.build(),
AsyncResponseTransformer.toFile(Paths.get("/osfile/myfile.pdf")));
futureGet.get();
} catch (URISyntaxException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
With above code I am getting exception stack trace as:
java.util.concurrent.ExecutionException: software.amazon.awssdk.core.exception.SdkClientException: Credentials must not be null.
at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895)
at com.aexp.ecp.vertx.spring.verticles.S3AsyncStreamOps.main(S3AsyncStreamOps.java:54)
Caused by: software.amazon.awssdk.core.exception.SdkClientException: Credentials must not be null.
at software.amazon.awssdk.core.exception.SdkClientException$BuilderImpl.build(SdkClientException.java:97)
at software.amazon.awssdk.core.internal.util.ThrowableUtils.asSdkException(ThrowableUtils.java:98)
at software.amazon.awssdk.core.internal.http.AmazonAsyncHttpClient$RequestExecutionBuilderImpl.execute(AmazonAsyncHttpClient.java:193)
at software.amazon.awssdk.core.internal.handler.BaseAsyncClientHandler.invoke(BaseAsyncClientHandler.java:263)
at software.amazon.awssdk.core.internal.handler.BaseAsyncClientHandler.doExecute(BaseAsyncClientHandler.java:205)
at software.amazon.awssdk.core.internal.handler.BaseAsyncClientHandler.execute(BaseAsyncClientHandler.java:134)
at software.amazon.awssdk.awscore.client.handler.AwsAsyncClientHandler.execute(AwsAsyncClientHandler.java:58)
at software.amazon.awssdk.services.s3.DefaultS3AsyncClient.getObject(DefaultS3AsyncClient.java:3949)
at com.aexp.ecp.vertx.spring.verticles.S3AsyncStreamOps.main(S3AsyncStreamOps.java:32)
Caused by: java.lang.NullPointerException: Credentials must not be null.
at software.amazon.awssdk.utils.Validate.paramNotNull(Validate.java:117)
at software.amazon.awssdk.auth.signer.params.Aws4SignerParams.<init>(Aws4SignerParams.java:42)
at software.amazon.awssdk.auth.signer.params.AwsS3V4SignerParams.<init>(AwsS3V4SignerParams.java:27)
at software.amazon.awssdk.auth.signer.params.AwsS3V4SignerParams.<init>(AwsS3V4SignerParams.java:21)
at software.amazon.awssdk.auth.signer.params.AwsS3V4SignerParams$BuilderImpl.build(AwsS3V4SignerParams.java:121)
at software.amazon.awssdk.auth.signer.AwsS3V4Signer.constructAwsS3SignerParams(AwsS3V4Signer.java:93)
at software.amazon.awssdk.auth.signer.AwsS3V4Signer.sign(AwsS3V4Signer.java:59)
at software.amazon.awssdk.core.internal.http.pipeline.stages.SigningStage.signRequest(SigningStage.java:63)
at software.amazon.awssdk.core.internal.http.pipeline.stages.SigningStage.execute(SigningStage.java:49)
at software.amazon.awssdk.core.internal.http.pipeline.stages.SigningStage.execute(SigningStage.java:35)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryExecutor.doExecute(AsyncRetryableStage.java:208)
at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryExecutor.execute(AsyncRetryableStage.java:107)
at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryExecutor.execute(AsyncRetryableStage.java:102)
at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage.execute(AsyncRetryableStage.java:78)
at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage.execute(AsyncRetryableStage.java:51)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncExecutionFailureExceptionReportingStage.execute(AsyncExecutionFailureExceptionReportingStage.java:41)
at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncExecutionFailureExceptionReportingStage.execute(AsyncExecutionFailureExceptionReportingStage.java:29)
at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncApiCallTimeoutTrackingStage.execute(AsyncApiCallTimeoutTrackingStage.java:64)
at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncApiCallTimeoutTrackingStage.execute(AsyncApiCallTimeoutTrackingStage.java:36)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.AmazonAsyncHttpClient$RequestExecutionBuilderImpl.execute(AmazonAsyncHttpClient.java:191)
... 6 more
I fixed this finally. It was a dependency issue between aws-sdk-java 2.10.56 and my previous sync aws-java-sdk-bundle 1.11.368. I created a separate project with only aws-sdk-java 2.10.56 and it started working properly. Able to read file from Object Storage and save on local system now.
I am using EWS-java-api to access an outlook email and read emails.
I am running into the following error:
microsoft.exchange.webservices.data.core.exception.service.remote.ServiceRequestException: The request failed. null
Here is my code:
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;
import microsoft.exchange.webservices.data.core.service.item.Item;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.search.FindItemsResults;
import microsoft.exchange.webservices.data.search.ItemView;
import microsoft.exchange.webservices.data.search.filter.SearchFilter;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
Properties properties = new Properties();
properties.put("javax.net.ssl.trustStore", "C:/Users/<path to java security>/cacerts" );
properties.put("javax.net.ssl.trustStorePassword","changeit");
System.setProperties(properties);
service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
def usr = "abc#mycompany.ca";
def pwd = "password";
def url = "https://mycompanydomain/ews/exchange.asmx";
service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
credentials = new WebCredentials(usr, pwd);
service.setCredentials(credentials);
try {
service.setUrl(new URI(url));
service.setTraceEnabled(true);
Calendar cal = Calendar.getInstance();
cal.roll(Calendar.MONTH, false);
view = new ItemView(50);
findResults = service.findItems(WellKnownFolderName.Inbox, view);
for(item in findResults.getItems()) {
println("\n + email is: "+item+ "\n") ;
}
} catch (Exception e) {
e.printStackTrace();
}
And here is the full stacktrace:
15:32:13 [INFO] ScriptProcessor starts processing...
microsoft.exchange.webservices.data.core.exception.service.remote.ServiceRequestException: The request failed. null
15:32:14 [INFO] ScriptProcessor processor executed in 889ms.
at microsoft.exchange.webservices.data.core.request.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:74)
at microsoft.exchange.webservices.data.core.request.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:158)
at microsoft.exchange.webservices.data.core.ExchangeService.findItems(ExchangeService.java:985)
at microsoft.exchange.webservices.data.core.ExchangeService.findItems(ExchangeService.java:1028)
at microsoft.exchange.webservices.data.core.ExchangeService.findItems(ExchangeService.java:1104)
at microsoft.exchange.webservices.data.core.ExchangeService$findItems$0.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
at Script1.run(Script1.groovy:54)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:585)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:623)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:594)
at org.webharvest.runtime.scripting.GroovyScriptEngine.eval(GroovyScriptEngine.java:136)
at org.webharvest.runtime.processors.ScriptProcessor.execute(ScriptProcessor.java:74)
at org.webharvest.runtime.processors.BaseProcessor.run(BaseProcessor.java:127)
at org.webharvest.runtime.Scraper.execute(Scraper.java:169)
at org.webharvest.runtime.Scraper.execute(Scraper.java:182)
at com.freedomoss.crowdcontrol.webharvest.executor.LocalWebharvestTaskExecutor.executeWebHarvestTask(LocalWebharvestTaskExecutor.java:182)
at com.workfusion.studio.launch.SingleThreadWebHarvestProcess.processTaskInputs(SingleThreadWebHarvestProcess.java:77)
at com.workfusion.studio.launch.SingleThreadWebHarvestProcess.start(SingleThreadWebHarvestProcess.java:46)
at com.workfusion.studio.launch.WebHarvestMainLauncher.launch(WebHarvestMainLauncher.java:79)
at com.workfusion.studio.launch.WebHarvestMainLauncher.main(WebHarvestMainLauncher.java:121)
Caused by: java.lang.NullPointerException
at com.ctc.wstx.sw.BaseStreamWriter.writeCharacters(BaseStreamWriter.java:447)
at microsoft.exchange.webservices.data.core.EwsUtilities.formatLogMessage(EwsUtilities.java:558)
at microsoft.exchange.webservices.data.core.ExchangeServiceBase.traceHttpRequestHeaders(ExchangeServiceBase.java:515)
at microsoft.exchange.webservices.data.core.request.ServiceRequestBase.buildEwsHttpWebRequest(ServiceRequestBase.java:686)
at microsoft.exchange.webservices.data.core.request.ServiceRequestBase.buildEwsHttpWebRequest(ServiceRequestBase.java:665)
at microsoft.exchange.webservices.data.core.request.ServiceRequestBase.validateAndEmitRequest(ServiceRequestBase.java:635)
at microsoft.exchange.webservices.data.core.request.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:62)
... 22 more
Any help is greatly appreciated.
i have face same issue in setting service url so i have done first by setting credentials and setup auto discovery
When this happens, instead of failing, the user can be prompted to accept the redirection or not. That functionality needs to be implemented inside the autodiscoverRedirectionUrlValidationCallback method. In the example below, it only checks to see that the redirection url starts with "https://". To accomplish this
static class RedirectionUrlCallback implements IAutodiscoverRedirectionUrl {
public boolean autodiscoverRedirectionUrlValidationCallback(
String redirectionUrl) {
return redirectionUrl.toLowerCase().startsWith("https://");
}
}
Now
service.autodiscoverUrl("<your_email_address>", new RedirectionUrlCallback());
can be called to deal with the redirection in a safe manner.
i am new in java... i am trying to read on modbus. PLC is slave device and it is configured well. my java file is unable to read modbus values.here is the code..given below. error is coming at master.init(); method. please help me in this case.
package com.mod4j;
import java.io.File;
import gnu.io.SerialPort;
import com.serotonin.io.serial.SerialParameters;
import com.serotonin.*;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.code.RegisterRange;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.locator.BaseLocator;
import com.serotonin.modbus4j.locator.NumericLocator;
import com.serotonin.modbus4j.msg.ReadCoilsRequest;
import com.serotonin.modbus4j.msg.ReadCoilsResponse;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import com.serotonin.modbus4j.msg.ReadInputRegistersRequest;
import com.serotonin.modbus4j.msg.ReadInputRegistersResponse;
import com.serotonin.modbus4j.msg.WriteCoilRequest;
import com.serotonin.modbus4j.msg.WriteCoilResponse;
import com.serotonin.modbus4j.msg.WriteRegistersRequest;
import com.serotonin.modbus4j.msg.WriteRegistersResponse;
import gnu.io.*;
public class Modbus4JTest
{
public static void main(String[] args) throws Exception
{
try
{
SerialParameters params = new SerialParameters();
params.setCommPortId("COM1");
params.setBaudRate(9600);
params.setDataBits(8);
params.setStopBits(1);
params.setParity(0);
ModbusFactory modbusFactory = new ModbusFactory();
ModbusMaster master = modbusFactory.createRtuMaster(params);
master.setTimeout(100);
master.setRetries(3);
byte [] RIR,RHR,RDI,RCR;
int slaveId=1;
int startOffset=0;
int numberOfRegisters=10;
int numberOfBits=10;
try
{
master.init();
while (true)
{
ReadInputRegistersRequest reqRIR = new ReadInputRegistersRequest(slaveId, startOffset, numberOfRegisters);
System.out.println("ReadInputRegistersRequest reqRIR =" +reqRIR);
ReadInputRegistersResponse resRIR = (ReadInputRegistersResponse) master.send(reqRIR);
RIR = resRIR.getData();
System.out.println("InputRegisters :" + RIR);
ReadHoldingRegistersRequest reqRHR = new ReadHoldingRegistersRequest(slaveId, startOffset, numberOfRegisters);
ReadHoldingRegistersResponse resRHR = (ReadHoldingRegistersResponse) master.send(reqRHR);
RHR=resRHR.getData();
System.out.println("HoldingRegister :" + RHR);
ReadDiscreteInputsRequest reqRDI= new ReadDiscreteInputsRequest(slaveId, startOffset, numberOfBits);
ReadCoilsResponse resRDI = (ReadCoilsResponse) master.send(reqRDI);
RDI=resRDI.getData();
System.out.println("DiscreteInput :" + RDI);
ReadCoilsRequest reqRCR = new ReadCoilsRequest(slaveId, startOffset, numberOfBits);
ReadCoilsResponse resRCR = (ReadCoilsResponse) master.send(reqRCR);
RCR=resRCR.getData();
System.out.println("CoilResponce :" + RCR);
short[] sdata = null;
WriteRegistersRequest reqWR = new WriteRegistersRequest(slaveId, startOffset, sdata);
WriteRegistersResponse resWR = (WriteRegistersResponse) master.send(reqWR);
int writeOffset = 0;
boolean writeValue = true;
WriteCoilRequest reqWC = new WriteCoilRequest(slaveId, writeOffset, writeValue);
WriteCoilResponse resWC = (WriteCoilResponse) master.send(reqWC);
Thread.sleep(1000);
}//end while
}//end try
catch (Exception e)
{
e.printStackTrace();
}//end catch
finally
{
master.destroy();
}//end finally
}//end try
catch (Exception e)
{
e.printStackTrace();
}//end catch
}// end main
}//end class Modbus4JTest
this is java file i am running.
and here are the error i have got after compiling..
please suggest what went wrong and please correct me at ...
is there any step by step tutorial or any demo video please give me link at
ayyaz.nadaf#gmail.com
Exception in thread "main" java.lang.NoClassDefFoundError:
jssc/SerialPortException
at com.serotonin.io.serial.SerialUtils.openSerialPort(SerialUtils.java:94)
at com.serotonin.modbus4j.serial.SerialMaster.init(SerialMaster.java:58)
at com.serotonin.modbus4j.serial.rtu.RtuMaster.init(RtuMaster.java:45)
at com.mod4j.Modbus4JTest.main(Modbus4JTest.java:58)
Caused by: java.lang.ClassNotFoundException: jssc.SerialPortException
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)
... 4 more
It appears you're using Modbus4J. It is based on jSSC (Java Simple Serial Connector) for serial communication, so make sure that jSSC is found while compiling (you may need to download it separately, since you're getting a ClassNotFoundException related to a jSSC class).
I don't know about any tutorial but I may suggest you to take a look at the Modbus4J forum archive. Here's a simple Modbus RTU example.
I am creating a Java web application. I added Jira API jars for connecting to Jira to get Issues created in Jira.
And this is my Java program to get the issues
import java.net.URI;
import java.net.URISyntaxException;
import com.atlassian.jira.rest.client.JiraRestClient;
import com.atlassian.jira.rest.client.NullProgressMonitor;
import com.atlassian.jira.rest.client.domain.Issue;
import com.atlassian.jira.rest.client.internal.jersey.JerseyJiraRestClientFactory;
public class AppJIRADataCollector {
final static JerseyJiraRestClientFactory factory = new JerseyJiraRestClientFactory();
public static void main(String args[])
{
AppJIRADataCollector appJira=new AppJIRADataCollector();
appJira.getIssues("http://localhost:8080/", "AP-1", "admin", "admin");
}
public void getIssues(String issueURI,String issueKey,String username, String password) {
try {
final URI jiraServerUri = new URI(issueURI);
final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri,username, password);
System.out.println(restClient);
final NullProgressMonitor pm = new NullProgressMonitor();
final Issue issue = restClient.getIssueClient()
.getIssue(issueKey, pm);
System.out.println(issue);
} catch (URISyntaxException e) {
System.out.println("URI not found");
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
When I run this program, I am getting the output correctly as it prints the issues.
But when I run this as web application, and calling the getIssues() method from servlet, tomcat showing NoSuchMethodError
Here is the stack trace
java.lang.NoSuchMethodError: com.google.common.collect.Iterables.contains(Ljava/lang/Iterable;Ljava/lang/Object;)Z
com.atlassian.jira.rest.client.internal.json.IssueJsonParser.parse(IssueJsonParser.java:216)
com.atlassian.jira.rest.client.internal.json.IssueJsonParser.parse(IssueJsonParser.java:59)
com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient$1.call(AbstractJerseyRestClient.java:85)
com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.invoke(AbstractJerseyRestClient.java:54)
com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.getAndParse(AbstractJerseyRestClient.java:80)
com.atlassian.jira.rest.client.internal.jersey.JerseyIssueRestClient.getIssue(JerseyIssueRestClient.java:131)
com.atlassian.jira.rest.client.internal.jersey.JerseyIssueRestClient.getIssue(JerseyIssueRestClient.java:123)
com.domain.jirademo.adapters.AppJIRADataCollector.getIssues(AppJIRADataCollector.java:22)
com.domain.jirademo.controllers.ProjectDefectsServlet.doPost(ProjectDefectsServlet.java:50)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Why this is happening? Any problem with JARs? I am using maven. If want I will post the pom also.
EDIT
I added the main method later only. So in the stack trace, line 22 refers to
final Issue issue = restClient.getIssueClient()
.getIssue(issueKey, pm);
NoSuchMethodError it's caused by a version mismatch, you should check your version of guava library.
I have a interesting problem.
When I started glassfish server, everythings work fine. But, I changed some code and published the server, and I run my client (SistemGirisClientKullaniciDogrula). The application throws this exception:
java.lang.ClassCastException: tr.com.app.Kullanici cannot be cast to tr.com.app.Kullanici.
Interesting part is, after the Glassfish server restart, application works fine.
I am using restlet-spring-hibernate. And I am also using JAXB (org.restlet.ext.jaxb.jar) for converting XML to Java objects. My application server is Glassfish v3.0
detail for congiguration
restlet 2.0.5
spring 3.0.5
hibernate 3.3.2
glassfish v3.0
client class(Just for test)
import java.io.IOException;
import org.restlet.Client;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.ext.jaxb.JaxbRepresentation;
public class SistemGirisClientKullaniciDogrula {
public static void main(String[] Args) throws IOException {
String url = "http://localhost:8080/Project/sistemgirisws";
Client client = new Client(Protocol.HTTP);
Kullanici kullanici = new Kullanici();
kullanici.setKodu("1");
JaxbRepresentation<Kullanici> jaxbRepresentationSendingKullanici= new JaxbRepresentation<Kullanici>(MediaType.APPLICATION_XML, kullanici);
Request request = new Request(Method.GET, url, jaxbRepresentationSendingKullanici);
Response response = client.handle(request);
JaxbRepresentation<Kullanici> kullaniciResponse = new JaxbRepresentation<Kullanici>(response.getEntity(), Kullanici.class);
kullanici = kullaniciResponse.getObject();
System.out.println("kullanici id : " + kullanici.getId());
}
}
Web Service
public class ProjectWebService {
/**
*
* #param representation
* #return
*/
#Get
public Representation getKullanici(Representation representation) {
JaxbRepresentation<Kullanici> jaxbRepresentation = new JaxbRepresentation<Kullanici>(representation, Kullanici.class);
Kullanici kullanici = new Kullanici();
try {
kullanici = jaxbRepresentation.getObject(); //THIS LINE THROW java.lang.classCastException tr.com.app.Kullanici cannot be cast to tr.com.app.Kullanici.
} catch (IOException e) {
e.printStackTrace();
}
try {
kullanici = sistemGirisBusinessManager.kullaniciDogrula(kullanici);
getResponse().setStatus(Status.SUCCESS_OK);
return new JaxbRepresentation<Kullanici>(MediaType.APPLICATION_XML, kullanici);
} catch (Exception exception) {
exception.printStackTrace();
getResponse().setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED);
return new JaxbRepresentation<MesajList>(MediaType.APPLICATION_XML, sistemGirisBusinessManager.getMesajList());
}
}
}
Does Anyone know what the problem is?
This could be a class loading issue. In Java, If two classloaders have loaded the same class, then it is treated as two different classes. In that case, your casting will fail because it seems to the JVM that you are casting one type to another which is not in an inheritance tree.
What must be happening is that when you modify your class, it gets loaded into a different classloader, where as the web service uses the original one.
Problem indeed in different class loaders. i've had it too and adding implements Serializable and serialVersionUID for those object solved the problem.