apache camel/redhat Fuse - http4 component - proxy not working - apache-camel

I am trying to invoke api over internet in our project. It is working while running locally but upon deployment we are getting connection time out error. Please help
My route:
<camelContext id="camel"
xmlns="http://camel.apache.org/schema/spring" trace="true">
<properties>
<property key="https.proxyHost" value="{{proxyHost}}" />
<property key="https.proxyPort" value="{{proxyPort}}" />
</properties>
<route>
<from id="route-timer" uri="timer://foo?repeatCount=1"/>
<setHeader headerName="Exchange.HTTP_METHOD">
<simple>POST</simple>
</setHeader>
<setHeader headerName="Content-Type">
<simple>application/x-www-form-urlencoded</simple>
</setHeader>
<setBody>
<simple>{{request.payload}}</simple>
</setBody>
<to uri="https4://demo.perfios.com/KuberaVault/insights/institutions?connectTimeout=100000" />
</route>
</camelContext>
We are using openshift platform for deployment and curl is working fine on OCP pod. But route execution is failing. Proxy is already set on pod level but still it is failing.
Error:
Message History
---------------------------------------------------------------------------------------------------------------------------------------
RouteId ProcessorId Processor Elapsed (ms)
[supportedInstituti] [supportedInstituti] [timer://foo?repeatCount=1 ] [ 100494]
[supportedInstituti] [log1 ] [log ] [ 8]
[supportedInstituti] [setHeader1 ] [setHeader[Exchange.HTTP_METHOD] ] [ 2]
[supportedInstituti] [setHeader2 ] [setHeader[Content-Type] ] [ 0]
[supportedInstituti] [setHeader3 ] [setHeader[CamelHttpQuery] ] [ 1]
[supportedInstituti] [setBody1 ] [setBody[simple{payload=<payload><apiVersion>2.1</apiVersion><destination>accou] [ 205]
[supportedInstituti] [to1 ] [https4://demo.perfios.com/KuberaVault/insights/institutions?connectTimeout=100] [ 100274]
Stacktrace
---------------------------------------------------------------------------------------------------------------------------------------
org.apache.http.conn.ConnectTimeoutException: Connect to demo.perfios.com:443 [demo.perfios.com/35.154.198.217] failed: connect timed out
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:151)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at org.apache.camel.component.http4.HttpProducer.executeMethod(HttpProducer.java:334)
at org.apache.camel.component.http4.HttpProducer.process(HttpProducer.java:193)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:148)
at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:181)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:548)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:138)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:101)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
at org.apache.camel.component.timer.TimerConsumer.sendTimerExchange(TimerConsumer.java:197)
at org.apache.camel.component.timer.TimerConsumer$1.run(TimerConsumer.java:79)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
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)
Curl command on OCP pod is working fine:
oc rsh testadapter-1-gtwkm
sh-4.2$ curl -kv https://demo.perfios.com/KuberaVault/insights/institutions
* About to connect() to proxy <<host>> port <<port>> (#0)
* Trying 157.227.4.5...
* Connected to <<host>> port <<port>>(#0)
* Establish HTTP proxy tunnel to demo.perfios.com:443
> CONNECT demo.perfios.com:443 HTTP/1.1
> Host: demo.perfios.com:443
> User-Agent: curl/7.29.0
> Proxy-Connection: Keep-Alive
>
< HTTP/1.1 200 Connection established
<
* Proxy replied OK to CONNECT request
* Initializing NSS with certpath: sql:/etc/pki/nssdb
* skipping SSL peer certificate verification
* SSL connection using TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
* Server certificate:
* subject: CN=*.perfios.com,O=Perfios Software Solutions Pvt Ltd,L=Bengaluru,ST=Karnataka,C=IN
* start date: Sep 29 00:00:00 2021 GMT
* expire date: Oct 30 23:59:59 2022 GMT
* common name: *.perfios.com
* issuer: CN=DigiCert SHA2 Secure Server CA,O=DigiCert Inc,C=US
> GET /KuberaVault/insights/institutions HTTP/1.1
> User-Agent: curl/7.29.0
> Host: demo.perfios.com
> Accept: */*
>
< HTTP/1.1 400 400
< Date: Sun, 17 Apr 2022 11:17:54 GMT
< Server: Apache
< Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
< Set-Cookie: JSESSIONID=BB7B2319BF8B42600F846305D2E50DEC; Path=/KuberaVault; Secure; HttpOnly
< Content-Length: 97
< Connection: close
< Content-Type: application/xml;charset=UTF-8
<
**<Error>
<code>BadParameter</code>
<message>Payload is required but missing</message>**
* Closing connection 0
</Error>sh-4.2$

Related

Content-Type validation in camel REST DSL

I have a Camel Spring Boot application that exposes a REST endpoint for which i only want to support media type of "application/json". My REST DSL configuration is as follows -
restConfiguration()
.component("netty-http")
.port(8081)
.bindingMode(RestBindingMode.json)
.clientRequestValidation(true)
.skipBindingOnErrorCode(true);
rest("/api")
.post("/earn")
.consumes("application/json")
.produces("application/json")
.bindingMode(RestBindingMode.json)
.to("direct:earn");
With this setup, i expect to receive a "415 Unsupported Media Type" response for a Content-Type other than "application/json". (https://camel.apache.org/manual/latest/rest-dsl.html#_client_request_validation)
"text/plain" is behaving as expected -
curl http://localhost:8081/api/earn -ik -XPOST --data '{"name":"abcd","points":20}' -H "Content-Type: text/plain"
HTTP/1.1 415 Unsupported Media Type
content-length: 0
Accept: */*
User-Agent: curl/7.55.1
content-type: text/plain
connection: keep-alive
But, on omitting the Content-Type header, the validation doesn't seem to kick in. The request is processed by the route and later fails during json parsing because body is missing.
curl http://localhost:8081/api/earn -ik -XPOST
HTTP/1.1 500 Internal Server Error
content-length: 15
Accept: */*
Long-Running-Action: A7A649D7ADDBD87-0000000000000037
User-Agent: curl/7.55.1
content-type: application/json
connection: keep-alive
With a Content-Type of "application/x-www-form-urlencoded" and a JSON payload, i get no reply at all -
curl http://localhost:8081/api/earn -ik -XPOST --data '{"name":"abcd","points":20}' -H "Content-Type: application/x-www-form-urlencoded"
curl: (52) Empty reply from server
and an exception on the server -
2021-09-14 14:35:49.807 DEBUG 12236 --- [erExecutorGroup] o.a.camel.component.netty.NettyConsumer : Channel: [id: 0xc93560d1, L:/0:0:0:0:0:0:0:1:8081 - R:/0:0:0:0:0:0:0:1:54534] received body: HttpObjectAggregator$AggregatedFullHttpRequest(decodeResult: success, version: HTTP/1.1, content: CompositeByteBuf(ridx: 0, widx: 27, cap: 27, components=1))
POST /api/earn HTTP/1.1
Host: localhost:8081
User-Agent: curl/7.55.1
Accept: */*
Content-Type: application/x-www-form-urlencoded
content-length: 27
2021-09-14 14:35:49.810 DEBUG 12236 --- [erExecutorGroup] o.a.c.c.netty.http.NettyHttpConsumer : Closing channel as an exception was thrown from Netty
java.lang.IllegalArgumentException: Invalid parameter, expected to be a pair but was {"name":"abcd","points":20}
at org.apache.camel.component.netty.http.DefaultNettyHttpBinding.populateCamelHeaders(DefaultNettyHttpBinding.java:279) ~[camel-netty-http-3.11.1.jar:3.11.1]
at org.apache.camel.component.netty.http.RestNettyHttpBinding.populateCamelHeaders(RestNettyHttpBinding.java:52) ~[camel-netty-http-3.11.1.jar:3.11.1]
at org.apache.camel.component.netty.http.DefaultNettyHttpBinding.toCamelMessage(DefaultNettyHttpBinding.java:100) ~[camel-netty-http-3.11.1.jar:3.11.1]
at org.apache.camel.component.netty.http.handlers.HttpServerChannelHandler.createExchange(HttpServerChannelHandler.java:351) ~[camel-netty-http-3.11.1.jar:3.11.1]
at org.apache.camel.component.netty.handlers.ServerChannelHandler.channelRead0(ServerChannelHandler.java:90) ~[camel-netty-3.11.1.jar:3.11.1]
at org.apache.camel.component.netty.http.handlers.HttpServerChannelHandler.channelRead0(HttpServerChannelHandler.java:224) ~[camel-netty-http-3.11.1.jar:3.11.1]
at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:99) ~[netty-transport-4.1.63.Final.jar:4.1.63.Final]
at org.apache.camel.component.netty.http.handlers.HttpServerMultiplexChannelHandler.channelRead0(HttpServerMultiplexChannelHandler.java:162) ~[camel-netty-http-3.11.1.jar:3.11.1]
at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:99) ~[netty-transport-4.1.63.Final.jar:4.1.63.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.63.Final.jar:4.1.63.Final]
at io.netty.channel.AbstractChannelHandlerContext.access$600(AbstractChannelHandlerContext.java:61) ~[netty-transport-4.1.63.Final.jar:4.1.63.Final]
at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:370) ~[netty-transport-4.1.63.Final.jar:4.1.63.Final]
at io.netty.util.concurrent.DefaultEventExecutor.run(DefaultEventExecutor.java:66) ~[netty-common-4.1.63.Final.jar:4.1.63.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) ~[netty-common-4.1.63.Final.jar:4.1.63.Final]
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.63.Final.jar:4.1.63.Final]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Spring boot version - 2.5.4, Camel - 3.11.1
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-spring-boot-dependencies</artifactId>
<version>3.11.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Netty http
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-netty-http-starter</artifactId>
</dependency>
How do i configure the route to consistently throw a 415 for all unsupported media types?

How do you add a cookie given after a post request in C?

I am trying to create a program that logs into a website for me. The problem is, when I follow the redirection the website supplies a unique cookie that I can't figure out how to add to the post request. I have been going through each of the libcurl options on the man page, but I can't find anything that will do this. So far this is the post request function that I have.
void webpost(char* url, char* postdata) {
CURL *handler = curl_easy_init();
CURLcode err;
long size = sizeof(postdata);
if (handler) {
curl_easy_setopt(handler, CURLOPT_URL, url);
curl_easy_setopt(handler, CURLOPT_POSTFIELDSIZE, 50L);
curl_easy_setopt(handler, CURLOPT_POSTFIELDS, postdata);
curl_easy_setopt(handler, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(handler, CURLOPT_VERBOSE, 1L);
err = curl_easy_perform(handler);
if (err != CURLE_OK) {
printf("ERROR POST: %s returned (%s)\n", url, curl_easy_strerror(err));
}
curl_easy_cleanup(handler);
}
}
When this function runs, I get the following result.
* Trying 10.10.10.10...
* TCP_NODELAY set
* Connected to website.com (10.10.10.10) port 2048 (#0)
> POST /login HTTP/1.1
Host: website.com
Accept: */*
Content-Length: 50
Content-Type: application/x-www-form-urlencoded
* upload completely sent off: 50 out of 50 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Moved temporarily
< Date: Wed, 26 Aug 2020 05:59:50 GMT
< Server: EZproxy
< Expires: Mon, 02 Aug 1999 00:00:00 GMT
< Last-Modified: Wed, 26 Aug 2020 05:59:50 GMT
< Cache-Control: no-store, no-cache, must-revalidate
< Cache-Control: post-check=0, pre-check=0
< Pragma: no-cache
< Set-Cookie: ezproxy=uRZWAo3IsKyR9O0; Path=/; Domain=.website.com
< Location: http://website.com/connect?session=suRZWAo3IsKyR9O0&url=menu
< Connection: close
<
* Closing connection 0
* Issue another request to this URL: 'http://website.com/connect?session=suRZWAo3IsKyR9O0&url=menu'
* Switch from POST to GET
* Hostname website.com was found in DNS cache
* Trying 10.10.10.10...
* TCP_NODELAY set
* Connected to website.com (10.10.10.10) port 2048 (#1)
> GET /connect?session=suRZWAo3IsKyR9O0&url=menu HTTP/1.1
Host: website.com
Accept: */*
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Moved temporarily
< Date: Wed, 26 Aug 2020 05:59:50 GMT
< Server: EZproxy
< Expires: Mon, 02 Aug 1999 00:00:00 GMT
< Last-Modified: Wed, 26 Aug 2020 05:59:50 GMT
< Cache-Control: no-store, no-cache, must-revalidate
< Cache-Control: post-check=0, pre-check=0
< Pragma: no-cache
< Set-Cookie: ezproxy=uRZWAo3IsKyR9O0; Path=/; Domain=.website.com
< Location: http://website.com/connect?session=ruRZWAo3IsKyR9O0&url=menu
< Connection: close
<
* Closing connection 1
* Issue another request to this URL: 'website.com/connect?session=ruRZWAo3IsKyR9O0&url=menu'
* Hostname website.com was found in DNS cache
* Trying 10.10.10.10...
* TCP_NODELAY set
* Connected to website.com (10.10.10.10) port 2048 (#2)
> GET /connect?session=ruRZWAo3IsKyR9O0&url=menu HTTP/1.1
Host: website.com
Accept: */*
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Wed, 26 Aug 2020 05:59:50 GMT
< Server: EZproxy
< Content-Type: text/html
< Connection: close
<
<html>
<head>
<title>Cookie Required</title>
</head>
<body>
<p>
Licensing agreements for these databases require that access be extended
only to authorized users. Once you have been validated by this system,
a "cookie" is sent to your browser as an ongoing indication of your authorization to
access these databases. This cookie only needs to be set once during login.
</p>
<p>
If you are using a firewall or network privacy program, you may need
reconfigure it to allow cookies to be set from this server.
</p>
<p>
As you access databases, they may also use cookies. Your ability to use those databases
may depend on whether or not you allow those cookies to be set.
</p>
<p>
To login again, click here.
</p>
</body>
</html>
* Closing connection 2
simply add a header in the next request to a site matching the domain and path parameters of the Set-cookie: header that says:
Cookie: ezproxy=uRZWAo3IsKyR9O0
That will be enough for the server to recognize and locate the session you come from, so it can locate the data belonging to your session.
You can read HTTP for a description of the status management mechanism and read about the Cookie and Set-Cookie headers.
Thank you, I was able to get it working by saving the cookie to a file and loading it in the same request.
curl_easy_setopt(handler, CURLOPT_COOKIEJAR, "cookies.txt");
curl_easy_setopt(handler, CURLOPT_COOKIEFILE, "cookies.txt");

IBM Social Business Toolkit - Create an activity

I am trying to create an activity by using IBM SBT but this does not work.
My IBM SBT version is 1.1.11.20151208-1200 (the latest).
The IBM Connections Version is 5.0 CR3.
I have had a look at the IBM example from:
IBM Documentation - Creating activities
I have the following code:
public static void testcreateData() throws ClientServicesException {
String serviceUrL = Variables.baseURL + "/activities/service/atom2/activities";
String content =
"<?xml version=\"1.0\" encoding=\"utf-8\"?> <entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:app=\"http://www.w3.org/2007/app\""
+ " xmlns:snx=\"http://www.ibm.com/xmlns/prod/sn\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\" xmlns:thr=\"http://purl.org/syndication/thread/1.0\">"
+ "<title type=\"text\">New</title>"
+ "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/type\" term=\"activity\" label=\"Activity\"/>"
+ "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/priority\" term=\"1\" label=\"Normal\"/>"
+ "<category term=\"tag1\" />" + "<category term=\"tag2\" />" + "<content type=\"html\">GoalOfActivity</content>"
+ "</entry>";
System.out.println( content );
Response res = Variables.anActivityService.createData( serviceUrL, null, content );
System.out.println( "Result: " + res.getResponse().getStatusLine().getStatusCode() );}
My XML output is the following:
<?xml version="1.0" encoding="utf-8"?> <entry xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns:snx="http://www.ibm.com/xmlns/prod/sn" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:thr="http://purl.org/syndication/thread/1.0"><title type="text">New</title><category scheme="http://www.ibm.com/xmlns/prod/sn/type" term="activity" label="Activity"/><category scheme="http://www.ibm.com/xmlns/prod/sn/priority" term="1" label="Normal"/><category term="tag1" /><category term="tag2" /><content type="html">GoalOfActivity</content></entry>
The error:
com.ibm.sbt.services.client.ClientServicesException: Request to url https://blabla.com/activities/service/atom2/activities returned an error response 415:Unsupported Media Type HTTP/1.1 415 Unsupported Media Type [Date: Wed, 13 Jan 2016 09:00:17 GMT, X-Frame-Options: SAMEORIGIN, Strict-Transport-Security: max-age=max-age=31536000;includeSubDomains, X-XSS-Protection: 1;mode=block, X-Permitted-Cross-Domain-Policies: master-only, X-Powered-By: Servlet/3.0, X-LConn-Auth: false, X-UA-Compatible: IE=9,8, Expires: Thu, 1 Jan 1970 00:00:00 GMT, Cache-Control: no-store, no-cache, must-revalidate, Accept: application/atom+xml, Set-Cookie: LtpaToken2=JYakBGXcJAWqNOfIc7PD5PKxpBf8spXAMh2RBtyQ/gCIFkLGuSFYLUq1Xkg335u3yLhI7lSuhNEQ4Y0j8DJB9DRr7jnQKNr8z6EwUs2Ak66eR4puAN5dvL+JiYsMj0Y9/QURoSALiLqkfWsByJpImJRRtEH8BHTaT811iaq/Cpux5h5XJ9uOPT420+4gqqzwuUyBc+71dLDs2XM/TwYx3ThTD+qA6nE42VFVszma7c4QmIrdvxASywOaFUQpCdLP63KTrs7NljOgqY82w0NNzcrz2VM3B4PUD5Fnht4HKkplB+7MBz4z1BDbwgc33BAdqNLKmd7b6vvFjAwDntIWAE7OL1rqP7k/w7rRgsqtUc1Ak074GhvkQvDjg89FeteKKG4Z7spfruNThmRWZ2IBiuQOj0cEb9LZwJMkcMrowpTWYxu0MTlcI+C9j3jV/xGK05hXvcYUmcm0HMpd0DJGE6e1J2uKEYaP7eoqjtScBtiVrGC1O1s8XXbw7vNcaUgsF0fc+3vCj0QZTJTxlNSixuRUxvRJHmTAkU7PpWMcmasTW2gQOOB6WtrST6j61865YUKSzMye8y73ps2n6+HAe87yVFNLBgm7omw+RMvCyKlhIE0go0bm2VrS2XUVMvPyT3vTo8Hlq5q1eYyzfwh2N56GhEc/H6c08Hh0K/9Mf+8=; Path=/; Domain=.blabla.com, Set-Cookie: JSESSIONID=0000MHOETW-Ow0ESyh_MllEfRId:1a17onpus; Path=/; HttpOnly, Vary: Accept-Encoding,User-Agent, Content-Length: 0, Keep-Alive: timeout=15, max=100, Connection: Keep-Alive, Content-Type: text/html, Content-Language: en-US]
I did a lot of research, but when I used code from the internet, I always got "400 Bad Request" - so I tried to focus on the IBM Documentation, but the code there does not work for me either.
Does anybody know how to do this?
Best regards

AngularJS / Alfresco / CORS filter issue: No 'Access-Control-Allow-Origin' header

I have some problem with Alfresco (5.0.d), my AngularJS (1.4.3) client and the CORS settings (typical cross-domain / No'Access-Control-Allow-Origin' header is present on the requested resource problem).
I am calling the Alfresco REST API from an AngularJS application running on localhost:3000, to an Alfresco instance running on localhost:8080 (Tomcat, no reverse-proxy in front).
This XHR call works fine:
http://localhost:8080/alfresco/service/slingshot/live-search-docs?t=Project&u=admin&pw=admin&alf_ticket=TICKET_9d9780c83b8b9525c7acb9d3d8da66c5c902fb76
This one
http://localhost:8080/alfresco/service/api/login?u=admin&pw=admin
only works fine in Internet Explorer 11, but in Chrome and Firefox, I am getting status code 200 returned with 0 bytes and the error in the JS console:
XMLHttpRequest cannot load
http://localhost:8080/alfresco/service/api/login?u=admin&pw=admin. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
In the Alfresco web.xml, I have enabled the CORS filter as follows:
<!-- CORS Filter Mappings Begin -->
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/api/*</url-pattern>
<url-pattern>/service/*</url-pattern>
<url-pattern>/s/*</url-pattern>
<url-pattern>/cmisbrowser/*</url-pattern>
</filter-mapping>
<!-- CORS Filter Mappings End -->
<!-- CORS Filter Begin -->
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowGenericHttpRequests</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.allowOrigin</param-name>
<!-- <param-value>http://localhost:3000 http://localhost:8081 http://localhost:8080 https://localhost</param-value> -->
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowSubdomains</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, HEAD, POST, PUT, DELETE, OPTIONS</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>origin, authorization, x-file-size, x-file-name, content-type, accept, x-file-type</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.maxAge</param-name>
<param-value>3600</param-value>
</init-param>
</filter>-->
<!-- CORS Filter End -->
The calls from within Angular:
The one that works fine:
$http.get('http://localhost:8080/alfresco/service/slingshot/live-search-docs?t=Project&alf_ticket=TICKET_9d9780c83b8b9525c7acb9d3d8da66c5c902fb76').then(function(response) {
console.log('DATA LOADED: ' + response.items);
$scope.contents = response.items;
});
Response headers:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Cache-Control: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Content-Length: 85
Date: Thu, 13 Aug 2015 06:37:24 GMT
The one that fails:
$http.get('http://localhost:8080/alfresco/service/api/login?u=' + $scope.user.email + '&pw=' + $scope.user.password).
then(function(response) {
console.log('ALF_TICKET: ' + response.data.ticket);
$scope.alfTicket = response.data.ticket;
$state.go('admin-panel.default.introduction');
}, function(response) {
console.log('LOGIN FAILED');
});
Response headers:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3000
Vary: Origin
Cache-Control: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 13 Aug 2015 06:38:36 GMT
I have the $httpProvider configured in my AngularJS app, just to be sure:
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
A CURL request simulated from a different host works fine, interestingly though, I do not get a Access-Control-Allow-Origin header back in the response despite the CORS filter enabled in Alfresco:
curl -H "Origin: http://www.microsoft.com" --verbose "http://alfresco.mycompany.ch:8080/alfresco/service/api/login?u=admin&pw=12#echo"
* Hostname was NOT found in DNS cache
* Trying 10.10.0.183...
* Connected to alfresco.mycompany.ch (10.10.0.183) port 8080 (#0)
> GET /alfresco/service/api/login?u=admin&pw=12#echo HTTP/1.1
> User-Agent: curl/7.37.1
> Host: alfresco.mycompany.ch:8080
> Accept: */*
> Origin: http://www.microsoft.com
>
< HTTP/1.1 200 OK
* Server Apache-Coyote/1.1 is not blacklisted
< Server: Apache-Coyote/1.1
< Cache-Control: no-cache
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Pragma: no-cache
< Content-Type: application/json;charset=UTF-8
< Content-Length: 85
< Date: Thu, 13 Aug 2015 08:11:15 GMT
<
{
"data":
{
"ticket":"TICKET_7d07634afbb25a7e823c0348d907e0790eeff97e"
}
}
* Connection #0 to host alfresco.mycompany.ch left intact
therefore I think it's client/AngularJS related.
=== Update 1: ===
I tried to add an interceptor to the $httpProvider as below, but it doesn't help. I don't see the headers I am setting there in any of the responses, although the interceptor gets called.
$httpProvider.interceptors.push(function() {
return {
'request': function(request) {
return request;
},
'response': function(response) {
console.log('Interceptor called.');
response.config.headers['MyTestHeader'] = '12345';
response.config.headers['Access-Control-Allow-Origin'] = '*';
return response;
}
};
});
=== Update 2: ===
Some more findings, but now a bit weird on the Alfresco side. I am doing two almost similar API calls, to the following two urls:
http://localhost:8080/alfresco/service/api/login
http://localhost:8080/alfresco/service/api/whatever
You can see, they only differ at the end. The one with /whatever returns a Access-Control-Allow-Origin response header, the one with /login does not. It must be related to the Alfresco config / webscript, but I have not yet found the origin of it.
curl -H "Origin: http://www.microsoft.com" --verbose "http://localhost:8080/alfresco/service/api/login"
* Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> GET /alfresco/service/api/login HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
> Origin: http://www.microsoft.com
>
< HTTP/1.1 400 Bad Request
< Server: Apache-Coyote/1.1
< Cache-Control: no-cache
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Pragma: no-cache
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Thu, 13 Aug 2015 12:49:46 GMT
< Connection: close
<
But this one:
curl -H "Origin: http://www.microsoft.com" --verbose "http://localhost:8080/alfresco/service/api/whatever"
* Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> GET /alfresco/service/api/whatever HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
> Origin: http://www.microsoft.com
>
< HTTP/1.1 404 Not Found
< Server: Apache-Coyote/1.1
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Origin: http://www.microsoft.com
< Vary: Origin
< Cache-Control: no-cache
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Pragma: no-cache
< Content-Type: text/html;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Thu, 13 Aug 2015 12:52:15 GMT
<
I also tried the CORS filter of Tomcat instead, same result.
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Questions:
(1) Am I missing something on the client/AngularJS $http side? Should I use a angular-http-interceptor? (Sorry, pretty new to AngularJS). I think that this is most probably the reason here, but not sure what's missing.
(2) I don't see why the CORS filter would not add the 'Access-Control-Allow-Origin' header to both responses but only to the one API call, since both API urls start with /alfresco/service, which should be handled by the CORS filter as per <url-pattern>/service/*</url-pattern>
(And why does it work for one API url, but for the other it does not? Only difference I see is that in one case, I am already authenticated and use an alf_ticket, in the other case I am not. But even if I add an (unnecessary) alf_ticket to the login call, it does not make any difference.)
(3) Why does it work in IE then at all? (by the way: with the Chrome extension https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi it also works in Chrome.)
Related SO question: cross domain call using REST Alfresco
I have the same issue, for some reason the login api "GET" call does not return "Access-Control-Allow-Origin" in the headers. WORKAROUND: The "POST" call works fine!
I faced similar issue and got it resolved by using "/alfresco/s/" instead of "/alfresco/service/".
In your case, try hitting using
http://localhost:8080/alfresco/s/api/login?u=admin&pw=admin.
Try if this works.

Jersey Server Sent Events not working with Accept-Encoding gzip

I am using Jersey 2.17 for SSE - I have the demo working per the docs: https://jersey.java.net/documentation/latest/sse.html.
In my tests, it works fine with simple curl requests (curl --verbose "localhost:9000/api/broadcast"), but if I add -H 'Accept-Encoding: gzip, deflate' (to replicate my javascript code) it doesn't work (eventually times out with 'transfer closed with outstanding read data remaining'). I'm guessing that jersey says its GZIPed the response, but really it hasn't.
My real problem is that the AngularJS javascript code always adds this Accept-Encoding... header.
I'm looking for a solution that will either
Prevent Accept-Encoding: gzip, deflate' from being added as Request Header when initialising the EventSource() object
Setup Jersey to correctly handle/gzip the events sent to the client.
Update - I've noticed that if I close the EventOutput object in Java code that my events are all sent.
This is the console output when using curl:
curl --verbose "localhost:9000/api/broadcast" -H 'Accept-Encoding: gzip, deflate'
* Hostname was NOT found in DNS cache
* Trying ::1...
* connect to ::1 port 9000 failed: Connection refused
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9000 (#0)
> GET /api/broadcast HTTP/1.1
> User-Agent: curl/7.37.1
> Host: localhost:9000
> Accept: */*
> Accept-Encoding: deflate, gzip
>
< HTTP/1.1 200 OK
* Server Apache-Coyote/1.1 is not blacklisted
< server: Apache-Coyote/1.1
< vary: Accept-Encoding
< content-encoding: deflate
< content-type: text/event-stream
< transfer-encoding: chunked
< date: Tue, 07 Apr 2015 20:35:42 GMT
< connection: close
<
* transfer closed with outstanding read data remaining
* Closing connection 0
curl: (18) transfer closed with outstanding read data remaining
For reference, my js code in my AngularJS app is:
$scope.sseSource = new EventSource('/api/ptt/1/status');
console.log( $scope.sseSource);
$scope.sseSource.onerror = function (event) {
console.log("onerror");
}
$scope.sseSource.onopen = function (event) {
console.log("onopen");
}
$scope.sseSource.onmessage = function (event) {
console.log("onmessage");
}

Resources