Jetty embedded -- error to load in SelectChannelConnector and setPort - jetty

I want to integrate jetty as module to be used as server for my application.
I m using maven to load dependencies for jetty as follow :
<dependency>
<groupId>org.eclipse.jetty.aggregate</groupId>
<artifactId>jetty-all</artifactId>
<version>9.3.7.v20160115</version>
</dependency>
And I'm following this tutorial to buil my server https://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty#Configuring_Connectors
here is the code I want to run :
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.AbstractConnector;
public class FileServer {
public static void main(String[] args) throws Exception {
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[]{"index.html"});
resource_handler.setResourceBase(".");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resource_handler, new DefaultHandler()});
server.setHandler(handlers);
server.start();
server.join();
}
}
However i've got errors in this part :
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
it cannot detect SelectChannelConnector neither setPort() !
Any help ? thanks

The giant red box at the start of that wiki page tells you ...
Jetty 7 and Jetty 8 are now EOL (End of Life)
All development and stable releases are being performed with Jetty 9.
This wiki is now officially out of date and all content has been moved to the Jetty Documentation Hub
Direct Link to updated documentation: http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html
In short, you can't use Jetty 8 code and mechanisms on Jetty 9.
Follow the link to the Jetty 9 documentation to see the up to date documentation and code examples

Related

How to install redisearch module in GCP memorystore redis instance

I need to install the RediSearch module on top of a GCP memorystore redis instance.
I followed the steps:
docker run -p 6379:6379 redislabs/redisearch:latest
I pushed this docker image to a Kubernetes cluster and exposed the external IP. I used that external IP and the 6379 port as configuration for my application but I'm not able to connect to RediSearch.
code:
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.redisearch.client.Client;
import io.redisearch.*;
public class RediSearch {
static Client client = new Client("testdoc1", "clusteripaddress", 8097);
private static final Logger LOG = LoggerFactory.getLogger(RediSearch.class);
public interface Options extends PipelineOptions {
#Description("gcp project id.")
#Default.String("XXXX")
String getProjectId();
void setProjectId(String projectId);
}
public static PipelineResult run(Options options) throws IOException {
Pipeline pipeline = Pipeline.create(options);
pipeline.apply(Create.of("test"))
.apply(ParDo.of(new DoFn<String, String>() {
private static final long serialVersionUID = 1L;
#ProcessElement
public void processElement(ProcessContext c) throws Exception {
String pubsubmsg = c.element();
Schema sc = new Schema()
.addTextField("title", 5.0)
.addTextField("body", 1.0)
.addNumericField("price");
client.createIndex(sc, Client.IndexOptions.Default());
Map<String, Object> fields = new HashMap<String, Object>();
fields.put("title", "hello world");
fields.put("body", "lorem ipsum");
fields.put("price", 800);
fields.put("price", 1337);
fields.put("price", 2000);
client.addDocument("searchdoc3", fields);
SearchResult[] res = client.searchBatch(new Query("hello world").limit(0, 5).setWithScores());
for (Document d : res[0].docs) {
LOG.info("redisearchlog{}",d.getId().startsWith("search"));
LOG.info("redisearchlog1{}",d.getProperties());
LOG.info("redisearchlog2{}",d.toString());
}
}
}));
return pipeline.run();
}
public static void main(String[] args) throws IOException {
Options options = PipelineOptionsFactory.fromArgs(args).as(Options.class);
run(options);
}
}
Error :
redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at redis.clients.jedis.util.Pool.getResource(Pool.java:59)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:234)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:15)
at io.redisearch.client.Client._conn(Client.java:137)
at io.redisearch.client.Client.getAllConfig(Client.java:275)
at com.testing.redisearch.RediSearch$1.processElement(RediSearch.java:59)
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: Failed connecting to host xxxxxxxxxxx:6379
at redis.clients.jedis.Connection.connect(Connection.java:204)
at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:100)
at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1894)
at redis.clients.jedis.JedisFactory.makeObject(JedisFactory.java:117)
at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:889)
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:424)
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:349)
at redis.clients.jedis.util.Pool.getResource(Pool.java:50)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:234)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:15)
at io.redisearch.client.Client._conn(Client.java:137)
at io.redisearch.client.Client.getAllConfig(Client.java:275)
at com.testing.redisearch.RediSearch$1.processElement(RediSearch.java:59)
at com.testing.redisearch.RediSearch$1$DoFnInvoker.invokeProcessElement(Unknown Source)
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement(SimpleDoFnRunner.java:218)
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement(SimpleDoFnRunner.java:183)
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement(SimpleParDoFn.java:335)
at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process(ParDoOperation.java:44)
at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process(OutputReceiver.java:49)
at org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.runReadLoop(ReadOperation.java:201)
at org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.start(ReadOperation.java:159)
at org.apache.beam.runners.dataflow.worker.util.common.worker.MapTaskExecutor.execute(MapTaskExecutor.java:77)
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.executeWork(BatchDataflowWorker.java:411)
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.doWork(BatchDataflowWorker.java:380)
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.getAndPerformWork(BatchDataflowWorker.java:305)
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.doWork(DataflowBatchWorkerHarness.java:140)
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call(DataflowBatchWorkerHarness.java:120)
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call(DataflowBatchWorkerHarness.java:107)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at redis.clients.jedis.Connection.connect(Connection.java:181)
... 31 more
Any solution is appreciated.
There are multiple causes as per the error JedisConnectionException: Could not get a resource from the pool. According to the answers in this question the problem is that the connection to RediSearch couldn't be established, be it because Redis is not running, the connection times out or it cannot be allocated.
Regardless, I have noticed that even though you deploy Redis on port 6379, in your code you are trying to access it on port 8097. Please change your Client declaration to the following and retry the connection.
static Client client = new Client("testdoc1", "<cluster_ip_address>", 6379);
If you are looking to have the RediSearch module in your memorystore instance, it appears that may not be supported yet. You can see in the google cloud docs here that at the time of writing this, even for version 5.0, redis modules are not supported.

Creating AmazonDynamoDBClient with AWSCredentials

We are developing a basic game for android phones and have recently switched from Eclipse IDE to Android Studios. With the switch, I was forced to move from aws-java-sdk-1.9.30 to aws-android-sdk-2.2.0.
I have attempted to update the AWS code and it is now compiling, however I have come across an issue while creating the AmazonDynamoDBClient.
I am getting this runtime error:
Exception in thread "main" java.lang.IllegalArgumentException: no HostnameVerifier specified
I'm not sure if I am missing a step somewhere. If anyone can help shed some light on what may be causing the issue, I will be very thankful!
On a related note, most of the examples I have been able to find, and the examples on which I based my initial code, seem to be for the aws-java-sdk-1.9.30 jars. If anyone knows of where I can find examples that are suited for the aws-android-sdk-2.2.0 jars, it would help immensely!
Here is the entire stack trace as requested:
CLIENT:com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient#5ef04b5
Creating Match Details...
Exception in thread "main" java.lang.IllegalArgumentException: no HostnameVerifier specified
at javax.net.ssl.HttpsURLConnection.setHostnameVerifier(HttpsURLConnection.java:265)
at com.amazonaws.http.UrlHttpClient.configureConnection(UrlHttpClient.java:169)
at com.amazonaws.http.UrlHttpClient.createConnection(UrlHttpClient.java:105)
at com.amazonaws.http.UrlHttpClient.execute(UrlHttpClient.java:60)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:361)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:211)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:2930)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.query(AmazonDynamoDBClient.java:1240)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.query(DynamoDBMapper.java:2181)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.query(DynamoDBMapper.java:2137)
at com.towerfield.aws.MatchDetails.getMatchIds(MatchDetails.java:201)
at com.towerfield.aws.MatchDetails.<init>(MatchDetails.java:109)
at com.towerfield.aws.MatchDetails.main(MatchDetails.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Process finished with exit code 1
Here is where the exception is thrown (inside HTTPSURLConnection.java):
public void setHostnameVerifier(HostnameVerifier v)
{
if (v == null)
{
throw new IllegalArgumentException("HostnameVerifier is null");
}
hostnameVerifier = v;
}
Here is the relevant code which seems to be causing the runtime error:
static AmazonDynamoDBClient client;
...
BasicAWSCredentials credentials = new BasicAWSCredentials("KEY","SECRETKEY");
client = new AmazonDynamoDBClient(credentials);
...
DynamoDBMapper mapper = new DynamoDBMapper(client);
...
List<PlayersListOfActiveMatches> latestReplies = mapper.query(PlayersListOfActiveMatches.class, queryExpression);
Here is a list of my imports as was requested:
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBAttribute;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBHashKey;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBQueryExpression;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBRangeKey;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBTable;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.Condition;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
DynamoDB examples for the AWS SDK for Android are available in the AWS documentation.

ElasticBeanstalk Client

I try to develop an elastic beanstalk client interface to connect through it to my amazon account elasticbeanstalk. I used my account's credentials from the script file credentials.Csl. I signed up to my account from Google chrome but I'm getting errors. Here is my code.
package PFE;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalkClient;
import com.amazonaws.services.elasticbeanstalk.model.CheckDNSAvailabilityResult;
public class Sample {
static AWSElasticBeanstalk eb;
private static void init()throws Exception{
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().getCredentials();
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (~/.aws/credentials), and is in valid format.",
e);
}
eb = new AWSElasticBeanstalkClient(credentials);
Region usWest2 = Region.getRegion(Regions.US_WEST_2);
eb.setRegion(usWest2);
}
public static void main(String[] args) throws Exception {
init();
try {
CheckDNSAvailabilityResult c= eb.checkDNSAvailability(null);
System.out.println("You have access to " + c.getAvailable() +
" Availability Zones.")
eb.createStorageLocation();
} catch (AmazonServiceException ase) {
System.out.println("Caught Exception: " + ase.getMessage());
System.out.println("Reponse Status Code: " + ase.getStatusCode());
System.out.println("Error Code: " + ase.getErrorCode());
System.out.println("Request ID: " + ase.getRequestId());
}
}
}
Here are the errors that I got when running my project
Exception in thread "main" java.lang.NoClassDefFoundError:org/apache/commons/logging/LogFactory at com.amazonaws.auth.profile.ProfilesConfigFile.<clinit>(ProfilesConfigFile.java:62) at com.amazonaws.auth.profile.ProfileCredentialsProvider.getCredentials(ProfileCredentialsProvider.java:106)
at PFE.Sample.init(Sample.java:29)
at PFE.Sample.main(Sample.java:47)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
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)
I thought the problem is with the org.apache.commons.logging.LogFactory library so I downloaded it and added it to my referenced libraries but I'm still getting the same errors.
I got the same error while trying to make a SQS sample... My solution is: Don't add AWS SDK for Java as as an external jar
But as a library.
Instructions for NetBeans IDE:
Download "SDK for Java" from this page
Extract all files from archive for example in folder /aws-java-sdk-1.9.22
Copy next files to your project:
/aws-java-sdk-1.9.22/lib/aws-java-sdk-1.9.22.jar
All *.jar files from folder: /aws-java-sdk-1.9.22/third-party/
Now, just add all *.jar files to your project in NetBeans IDE.
Profit!
The problem was that there are other missing libraries, so i installed the toolkit AWS for my Eclipse Kepler , with all necessary libraries.
http://aws.amazon.com/fr/eclipse/ ..link for download.

try to use xfire client to retrieve data from DSS sample

I am going through the RDBMS sample of data service server now. the service is in 'localhost:9763/services/RDBMSSample?wsdl` and works fine. so I want to use a Xfire client to test the service and for further use. here is my code:
import java.net.URL;
import org.codehaus.xfire.client.Client;
public class CaClient {
public static void main(String[] args) throws Exception {
try {
String s = System.getProperty("java.runtime.version");
Client client = new Client(new URL("http://***:9763/services/RDBMSSample?wsdl"));
Object[] results = client.invoke("productsInfo", new Object[]{null});
System.out.println(results[0]);
}
finally {
}
}
}
Then, I run this sample code in eclipse but get the following error:
06, 2013 4:16:33 org.codehaus.xfire.transport.http.HttpChannel sendViaClient
SEVERE: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
How can I disable the SSL?

how to create httpprovider for another server

i tried to create httpprovider in eclipe and when run in wowza media server it does not load properly it returns only wowza server version.
code of eclipse is here
package com.domain.appname;
import java.io.IOException;
import java.io.OutputStream;
import com.wowza.wms.vhost.IVHost;
import com.wowza.wms.http.HTTProvider2Base;
import com.wowza.wms.http.IHTTPRequest;
import com.wowza.wms.http.IHTTPResponse;
public class CreateApp extends HTTProvider2Base {
public void onHTTPRequest(IVHost inVhost, IHTTPRequest req, IHTTPResponse resp){
String ret = req.getQueryString();
resp.setHeader("Content-Type", "text/xml");
OutputStream out = resp.getOutputStream();
byte[] outBytes = ret.toString().getBytes();
try {
out.write(outBytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and also set vhost file as
<HTTPProvider>
<BaseClass>com.domain.appname.CreateApp</BaseClass>
<RequestFilters>CreateProducerApp*</RequestFilters>
<AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>
Please help
Without seeing your complete vhost.xml, my guess would be that you put your new HTTPProvider last in the list of HTTPProviders.
When the server processes http requests it starts at the first one and tries each one. The RequestFilter for the provider that returns the server info is "*" which means no providers after this one will get called. This is usually the last one. Do make sure yours is before this one.
Please put your HTTPProvider entry in vHosts file before following block:
<HTTPProvider>
<BaseClass>com.wowza.wms.http.HTTPServerVersion</BaseClass>
<RequestFilters>*</RequestFilters>
<AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>
Otherwise all of your request will give Wowza version details.
So, your final vhost file's end should look like:
<HTTPProvider>
<BaseClass>com.domain.appname.CreateApp</BaseClass>
<RequestFilters>CreateProducerApp*</RequestFilters>
<AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>
<HTTPProvider>
<BaseClass>com.wowza.wms.http.HTTPServerVersion</BaseClass>
<RequestFilters>*</RequestFilters>
<AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>