How to add parent Context in jetty - jetty

I wrote a contexthandler to map http://hostname:9001/gm/test as follow:
public static void main(String[] args) throws Exception {
Server server = new Server(new QueuedThreadPool(8, 6));
ServerConnector connector = new ServerConnector(server);
connector.setPort(9001);
server.setConnectors(new Connector[] { connector });
HandlerCollection handler = new HandlerCollection();
ContextHandler contextHandler = new ContextHandler("/gm");
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] { new TestHandler("/test") });
contextHandler.setHandler(contexts);
handler.setHandlers(new Handler[] { contextHandler, new DefaultHandler() });
server.setHandler(handler);
server.start();
server.dumpStdErr();
server.join();
}
but it doesn't work. If I remove var contextHandler in up codes. request http://localhost:9001/test it work. invoked Testhandle.doHandle(). if I want add parent context path to all contextHandlers in ContextHandlerCollection, how to do it ?

A nested ContextHandlerCollection is not a context of its own, and are not additive to parent contexts.
A Handler only knows about itself and below, not what is above it.
Your code essentially says the following
Server
+ HandlerCollection
+ ContextHandler "/gm"
| + ContextHandlerCollection
| + TestHandler "/test"
+ DefaultHandler
If the incoming request is on http://localhost:9001/gm/test then the processing of that request will hit the ContextHandler "/gm" and allow that sub-tree to be processed (as it matches the incoming request). Then it hits the TestHandler "/test" (Which I'm assuming does its own context path or target logic), and then doesn't match anymore as /gm/test != /test as the TestHandler knows nothing about the ContextHandler above it.
Your code could look like this ...
public static void main(String[] args) throws Exception {
Server server = new Server(new QueuedThreadPool(8, 6));
ServerConnector connector = new ServerConnector(server);
connector.setPort(9001);
server.setConnectors(new Connector[] { connector });
HandlerCollection handlers = new HandlerCollection();
server.setHandler(handlers);
ContextHandlerCollection contexts = new ContextHandlerCollection();
String baseContext = "/gm";
// map on "/gm/test"
contexts.addHandlers(new TestHandler(baseContext + "/test"));
// map on "/gm/foo"
contexts.addHandlers(new FooHandler(baseContext + "/foo"));
baseContext = "/odd";
// map on "/odd/bar"
contexts.addHandlers(new BarHandler(baseContext + "/bar"));
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler() });
server.start();
server.dumpStdErr();
server.join();
}

Related

Spring RestTemplate credential/Authorization in header getting 401-unauthorized, where in postman it is working fine

using postman, for a GET request with header values for user name and password
and successfully hitting a rest service and getting response 200.
But when trying to access same request by java code using spring RestTemplate getting 401-unauthorized issue.
this is the code
final String uri = "http://<host>:<port>/services/arecord";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("username", "admin");
String password = "admin";
map.add("password", password);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
RestTemplate restTemplate = new RestTemplate();
try {
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET,
new HttpEntity(createHeaders("admin", "admin")), String.class);
String body = response.getBody();
} catch (HttpClientErrorException e) {
logger.info("****** ERROR *********** " + e.getMostSpecificCause());
return true;
}
I haven't tested it, but try something like this:
final String uri = "http://<host>:<port>/services/arecord";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("username", "admin");
headers.set("password", "admin");
HttpEntity entity = new HttpEntity(headers);
RestTemplate restTemplate = new RestTemplate();
try {
ResponseEntity<String> response = restTemplate.exchange(
uri, HttpMethod.GET, entity, String.class);
String body = response.getBody();
} catch (HttpClientErrorException e) {
logger.info("****** ERROR *********** " + e.getMostSpecificCause());
return true;
}

Error during web service call in Xamarin Forms

I've added connected service via Microsoft WCF Web Service Reference Provider (see picture) proxy class has been successfuly created.
Then, when I try execute sample method from this web service (client.TestLanguageAsync() - which returns string) I get null reference exception - but I dont know what is null, because details of exception are very poor (look on picture). Below is code.
private async void BtnTest_Clicked(object sender, EventArgs e) {
try {
var endpoint = new EndpointAddress("https://f9512056.f95.ficosa.com/WMS/WMSWebService.asmx");
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport) {
Name = "basicHttpBinding",
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647
};
TimeSpan timeout = new TimeSpan(0, 0, 30);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
WMSWebServiceSoapClient client = new WMSWebServiceSoapClient(binding, endpoint);
string text = await client.TestLanguageAsync(); //This causes exception
label.Text = text;
} catch (Exception E) {
label.Text = E.ToString();
}
}
Look also on screen
Adding service reference and exception screen
Any ideas? Thanks in advance:)

Using Httpclient for send SOAP request In Asp.net Core

Im using Asp.net Core, for calling an asmx service which has 4 methods and i want to call one of them by the name: Verify method, i do this steps:
1-Create realted SOAP:
private XmlDocument CreateSoapEnvelope(PayVM payModel)
{
XmlDocument soapEnvelop = new XmlDocument();
string requiredXML = string.Format(#"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/1999/XMLSchema""><SOAP-ENV:Body><verifyTransaction xmlns=""http://tempuri.org/""> <String_1 xsi:type=""xsd:string"">{0}</String_1><String_2 xsi:type=""xsd:string"">{1}</String_2></verifyTransaction></SOAP-ENV:Body></SOAP-ENV:Envelope>", payModel.ReNO, payModel.MID);
soapEnvelop.LoadXml(requiredXML);
return soapEnvelop;
}
2-create the HttpClient and send my request:
XmlDocument soapRequest = CreateSoapEnvelope(iPGVerifyResultModel);
using (var client = new HttpClient())
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri("relatedUri/ServiceName.asmx"),
Method = HttpMethod.Post
};
request.Content = new StringContent(soapRequest.ToString(), Encoding.UTF8, "text/xml");
request.Headers.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
request.Headers.Add("SOAPAction", "Verify"); //I want to call this method
HttpResponseMessage response = client.SendAsync(request).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception();
}
Task<Stream> streamTask = response.Content.ReadAsStreamAsync();
Stream stream = streamTask.Result;
var sr = new StreamReader(stream);
var soapResponse = XDocument.Load(sr);
//do some other stuff...
}
but i didn't result, i try uses service by same parameters with Soap UI and the service work properly, but in my way i got StatusCode: 400 what is the problem?

Embedded jetty implementing HttpSessionListener

I am trying to implementing HttpSessionListener interface with embedded jetty with proxy servlet, I have registered SessionListener, but it is not getting invoked at all, here is the code,
public class JettyProxy {
public static void main(String[] args) throws Exception {
Server server = new Server();
CustomProxyServlet customProxyServlet = new CustomProxyServlet();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8888);
server.addConnector(connector);
ConnectHandler proxy = new ConnectHandler();
server.setHandler(proxy);
ServletContextHandler context = new ServletContextHandler(proxy, "/",
ServletContextHandler.SESSIONS);
ServletHolder proxyServlet = new ServletHolder(customProxyServlet);
context.addServlet(proxyServlet, "/*");
if (context.getSessionHandler() == null) {
System.out.println("Session handler is null");
} else {
System.out.println("Session handler is not null");
}
if (context.getSessionHandler().getSessionManager() == null) {
System.out.println("Managaer it null");
} else {
System.out.println("Manager is not null");
}
context.getSessionHandler().addEventListener(new CustomSessionHandler());
server.start();
server.join();
}
}
SessionHandler is not null, session creating events are not getting triggered, please help me, what is the procedure get session events?
you should have a SessionManager. i usually use :
org.eclipse.jetty.server.session.HashSessionManager.HashSessionManager()
and
org.eclipse.jetty.server.session.SessionHandler.SessionHandler(SessionManager manager)
then you should set the handler for the context
context.setHandler(sessionHandler);
sessionHandler.addEventListener("Your Session Listener");

Jetty embed in Processing.org, static assets + POST

I'm trying to embed Jetty in a Processing Sketch. So far I made it working to serve static files (a html directory in the Sketch folder).
I want to react to one POST with a user input from one of the static pages.
As I have no knowledge on Jetty and coming from a PHP & Ruby (RoR) web programing background I am very confused with the way things go in Jetty.
I simply want something similar to routes where everything except e.g.
"localhost:8080/post?string=whatever"
is a static file.
The post?string=whatever should maybe trigger a function (in Processing) where the submitted String is handled.
I have been reading the Jetty docs a lot but couldn't figure out so far how to do it.
Thank you very much for any help!
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
String poststr;
void setup() {
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(sketchPath("")+"pftf");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] {
resource_handler, new DefaultHandler()
}
);
server.setHandler(handlers);
try {
server.start();
server.join();
}
catch(Exception e) {
};
}
Yes, Jetty can be very confusing in the beginning, especially when you only want to do a couple of simple things (not necessarily full-blown web applications).
The key to making this work is to use a ContextHandler for each of your other handlers (e.g. ResourceHandler). You can tell the ContextHandler which context (i.e. URL) it should respond to. After making a ContextHandler for the ResourceHandler and your custom Handler (e.g. PostHandler) you have to put both in a ContextHandlerCollection (uff...), so your Server knows what contexts exist.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
void setup() {
/* Configure the http server */
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
/* Resources */
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
resourceHandler.setWelcomeFiles(new String[] {
"index.html"
}
);
resourceHandler.setResourceBase(sketchPath("")+"pftf");
ContextHandler resourceContext = new ContextHandler();
resourceContext.setContextPath("/");
resourceContext.setHandler(resourceHandler);
/* Post API */
PostHandler postHandler = new PostHandler();
ContextHandler postContext = new ContextHandler();
postContext.setContextPath("/post");
postContext.setHandler(postHandler);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] {
resourceContext, postContext
}
);
server.setHandler(contexts);
/* Start the server (finally) */
try {
server.start();
server.join();
}
catch(Exception e) {
println("Could not start http server. Reason: " + e.toString());
};
}
void printCard(String mtext) {
println("Printing card with text: " + mtext);
}
Your PostHandler could look something like this:
public class PostHandler extends AbstractHandler
{
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
String stringParameter = request.getParameter("string");
/* Check if the string parameter is there and not empty */
if (stringParameter != null && !stringParameter.trim().equals("")) {
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<h1>You sent me: " + stringParameter + "</h1>");
println("Received a string via /post: " + stringParameter);
printCard(stringParameter);
}
else {
// Parameter is missing
response.setStatus(HttpServletResponse.SC_BAD_REQUEST );
baseRequest.setHandled(true);
response.getWriter().println("<h1>Error: Missing string parameter</h1>");
println("Missing string via /post.");
}
}
}