I want to force https url when http url was requested. I found this in prettyfaces forum. but this code give cannot find symbol error. how can I fix this ?
return ConfigurationBuilder.begin()
.addRule()
.when(URL.captureIn("url").and(Path.matches("/login")).and(Scheme.matches("http")))
.perform(Redirect.permanent(URL.capturedWith("url").toScheme("https")));
Try using a parameter Transposition:
return ConfigurationBuilder.begin()
.addRule()
.when(URL.captureIn("url").and(Path.matches("/login")).and(Scheme.matches("http")))
.perform(Redirect.permanent("{url}"))
.where("url").transposedBy(new Transposition() { ... convert to HTTPS HERE ... });
https://github.com/ocpsoft/rewrite/blob/master/api/src/main/java/org/ocpsoft/rewrite/param/Transposition.java
You can also achieve the same thing by doing something like this with a custom Operation:
https://github.com/ocpsoft/rewrite/blob/master/config-servlet/src/test/java/org/ocpsoft/rewrite/servlet/config/SchemeChangeConfigurationProvider.java
public class SchemeChangeConfigurationProvider extends HttpConfigurationProvider
{
#Override
public int priority()
{
return 0;
}
#Override
public Configuration getConfiguration(final ServletContext context)
{
Configuration config = ConfigurationBuilder.begin()
.addRule().when(Scheme.matches("http")).perform(new HttpOperation() {
#Override
public void performHttp(HttpServletRewrite event, EvaluationContext context)
{
String url = event.getRequest().getRequestURL().toString().replaceFirst("http", "https");
Redirect.temporary(url).perform(event, context);
}
});
return config;
}
}
Related
I ran across this url which suggests that an Http Handler can be added(Example is in Spring 1.x). https://lists.jboss.org/pipermail/undertow-dev/2017-March/001938.html
I have tried adding the following code - it does not appear to be called unless I add a listener. Unfortunately, Spring appears to have already added a listener. What would like to do is updates Spring's listener with my Http Handler. I am just not sure how to do it.
Any help is very much appreciated.
#Component
#Slf4j
public class LibCoreEmbeddedServletCustomerizer implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
#Value("${same.site.string}")
private String sameSiteString;
#Value("${server.port}")
private int serverPort;
#Value("${server.address}")
private String serverAddress;
#Override
public void customize(UndertowServletWebServerFactory factory) {
factory.addBuilderCustomizers(new UndertowBuilderCustomizer() {
#Override
public void customize(Undertow.Builder builder) {
log.debug("LibCoreEmbeddedServletCustomerizer::customize");
UndertowBuilderCustomizer customizer = new UndertowBuilderCustomizer() {
#Override
public void customize(Undertow.Builder builder) {
builder.
//addHttpListener(serverPort, serverAddress)
setHandler(new HttpHandler() {
#Override
public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
Map<String, Cookie> cookies = httpServerExchange.getResponseCookies();
log.debug(Encode.log(String.format("UndertowServletWebServerFactory handleRequest sameSiteString=%s", sameSiteString)));
for (Cookie cookie:cookies.values()) {
log.debug(Encode.log(String.format("UndertowServletWebServerFactory handleRequest cookie=%s", cookie)));
cookie.setSameSiteMode(sameSiteString);
}
}
});
}
};
factory.addBuilderCustomizers(customizer);
}
});
}
}
Try this:
SameSiteHandler goes through all of response cookies and moves SameSite information from Comment To SameSiteMode property.
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.Cookie;
import lombok.RequiredArgsConstructor;
#RequiredArgsConstructor
public class SameSiteHandler implements HttpHandler {
private final HttpHandler nextHttpHandler;
#Override
public void handleRequest(HttpServerExchange httpHandlerExchange) throws Exception {
httpHandlerExchange.addResponseCommitListener(exchange -> {
var cookies = exchange.getResponseCookies();
if (cookies != null) {
cookies.forEach((name, cookie) -> fix(cookie)));
}
});
nextHttpHandler.handleRequest(httpHandlerExchange);
}
/** Moves SameSite value from Comment to SameSiteMode */
private void fix(Cookie cookie) {
if (cookie == null) {
return;
}
var comment = cookie.getComment();
cookie.setComment(null);
cookie.setSameSiteMode(comment);
}
}
Register SameSiteHandler
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Configuration;
#Configuration
public class SameSiteHandlerConfig implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
#Override
public void customize(UndertowServletWebServerFactory factory) {
factory.addDeploymentInfoCustomizers(deploymentInfo ->
deploymentInfo.addInitialHandlerChainWrapper(SameSiteHandler::new));
}
}
I want to call webservices via clients. The clients are instantiated as beans:
#Configuration
public class ServiceClientConfiguration {
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath(CONTEXT_PATH);
return marshaller;
}
#Bean
public Service1Client authenticate(Jaxb2Marshaller marshaller) {
Service1Client client = new Service1Client();
client.setDefaultUri("http://localhost:8292/service1");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
#Bean
public Service2Client broker(Jaxb2Marshaller marshaller) {
Service2Client client = new Service2Client();
client.setDefaultUri("http://localhost:8192/service2");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
Though the both of the services are different, the request and responses are defined via xsd-files to the same package name - which is provided here as String 'CONTEXT_PATH' to the marshaller.
The clients itself look like this:
public class Service1Client extends WebServiceGatewaySupport {
private static final Logger log = LoggerFactory.getLogger(Tools.getClassName());
public Service1Response process(Service1Request request) {
Service1Response response = null;
try {
response = (Service1Response) getWebServiceTemplate()
.marshalSendAndReceive("http://localhost:8292/service1", request);
} catch (Exception e) {
log.error("", e);
}
return response;
}
}
and
public class Service2Client extends WebServiceGatewaySupport {
private static final Logger log = LoggerFactory.getLogger(Tools.getClassName());
public Service2Response process(Service2Request request) {
Service2Response response = null;
try {
response = (Service2Response) getWebServiceTemplate()
.marshalSendAndReceive("http://localhost:8192/service2", request);
} catch (Exception e) {
log.error("", e);
}
return response;
}
}
While running Service1Client is fine, the Service2Client fails with
javax.xml.bind.JAXBException: class <package>.Service2Request nor any of its super class is known to this context.
I removed "Service1Client" from the code - but the error remained to be the same.
I have renamed the pathname of the CONTEXT_PATH. It was "types.". I changed it to "dto.". Now it works as expected.
For me the reason for the problem looks sort of strange - maybe somebody can explain it.
I am trying to register a ICustomVirtualPathProvider in one of my modules. This is what I am trying to use:
public class AzureVirtualPathProvider : VirtualPathProvider, ICustomVirtualPathProvider
{
public IStaticDataStorageProvider StaticDataStorageProvider { get; set; }
public VirtualPathProvider Instance
{
get
{
return this;
}
}
public AzureVirtualPathProvider(IStaticDataStorageProvider staticDataStorageProvider)
{
StaticDataStorageProvider = staticDataStorageProvider;
}
public override bool FileExists(string virtualPath)
{
if (!virtualPath.Contains("StaticData")) return base.FileExists(virtualPath);
return true;
}
public override VirtualFile GetFile(string virtualPath)
{
if (!virtualPath.Contains("StaticData") || !StaticDataStorageProvider.IsCloud()) return base.GetFile(virtualPath);
return new CustomVirtualFile(StaticDataStorageProvider, virtualPath);
}
}
so in Module.Load I am setting:
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AzureVirtualPathProvider>().PropertiesAutowired().As<ICustomVirtualPathProvider>();
}
but this has not been picked up when Orchard calls this line in OrchardStartup.cs (in Orchard.Framework)
if (HostingEnvironment.IsHosted) {
foreach (var vpp in container.Resolve<IEnumerable<ICustomVirtualPathProvider>>()) {
HostingEnvironment.RegisterVirtualPathProvider(vpp.Instance);
}
}
I haver tried calling HostingEnvironment.RegisterVirtualPathProvider directly thus:
HostingEnvironment.RegisterVirtualPathProvider(new AzureVirtualPathProvider());
and tried to inject the dependency using property injecction:
builder.Register(c => new AzureVirtualPathProvider { StaticDataStorageProvider = c.Resolve<IStaticDataStorageProvider>() });
however the value for StaticDataStorageProvider is always null when AzureVirtualPathProvider is run.
I have tried moving AzureVirtualPathProvider to OrchardFramework but then it does not resolve StaticDataStorageProvider.
How do I get Orchard to load my CustomVirtualPathProvider?
In the end I did this:
public class OrchardShellEvents : IOrchardShellEvents
{
readonly ICustomVirtualPathProvider _customVirtualPathProvider;
public OrchardShellEvents(ICustomVirtualPathProvider customVirtualPathProvider)
{
_customVirtualPathProvider = customVirtualPathProvider;
}
public void Activated()
{
HostingEnvironment.RegisterVirtualPathProvider(_customVirtualPathProvider.Instance);
}
public void Terminating()
{
}
}
I don't know if this is the best solution but it worked and might help someone else.
I am trying to hit the api : www.xyz.com/abc_cc/cc/userregister/newuser
This is my Code :
public class MainActivity extends AppCompatActivity {
public static final String BASE_URL = "abc.com/abc_cc/cc/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(getUnsafeOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
Endpoints endpoints= retrofit.create(Endpoints.class);
endpoints.newuser("{\"full_name\":\"sss\",\"states_id\":\"20\",\"mobile\":\"9876543210\",\"password\":\"******\",\"accept_terms\":true,\"Userid\":\"0\",\"refer\":\"\",\"ip-address\":\"1.2.3.4\",\"device_type\":\"samsung J5\",\"os-version\":\"5.0.1\",\"client\":\"app\",\"secret_key\":\"44\"}")
.enqueue(new retrofit2.Callback<Items>() {
#Override
public void onResponse(retrofit2.Call<Items> call, retrofit2.Response<Items> response) {
System.out.println("onResponse : "+response.message());
System.out.println("onResponse : "+response.body());
System.out.println("onResponse : "+response.code());
System.out.println("onResponse : "+response.errorBody());
System.out.println("onResponse : "+response.isSuccessful());
System.out.println("onResponse : "+response.raw());
System.out.println("onResponse : "+response);
}
#Override
public void onFailure(retrofit2.Call<Items> call, Throwable t) {
System.out.println("onFailure"+call);
}
});
}
public static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
} };
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts,
new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext
.getSocketFactory();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient = okHttpClient.newBuilder()
.sslSocketFactory(sslSocketFactory)
.hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Interface :
public interface Endpoints {
#POST("/userregister/newuser")
#FormUrlEncoded
Call<Items> newuser(#Field("Data") String Data);
}
POJO class :
public class Items {
#SerializedName("Response-Status")
#Expose
private Boolean responseStatus;
#SerializedName("Response-Validate")
#Expose
private Boolean responseValidate;
#SerializedName("Response-Message")
#Expose
private String responseMessage;
#SerializedName("Response-Data")
#Expose
private ResponseData responseData;
public Boolean getResponseStatus() {
return responseStatus;
}
public void setResponseStatus(Boolean responseStatus) {
this.responseStatus = responseStatus;
}
public Boolean getResponseValidate() {
return responseValidate;
}
public void setResponseValidate(Boolean responseValidate) {
this.responseValidate = responseValidate;
}
public String getResponseMessage() {
return responseMessage;
}
public void setResponseMessage(String responseMessage) {
this.responseMessage = responseMessage;
}
public ResponseData getResponseData() {
return responseData;
}
public void setResponseData(ResponseData responseData) {
this.responseData = responseData;
}
}
I am getting this response :
{protocol=http/1.1, code=404, message=Not Found, url=www.xyz.com/userregister/newuser}
I have given the proper url then why is it taking only half of it?
I have tried the example from https://code.tutsplus.com/tutorials/sending-data-with-retrofit-2-http-client-for-android--cms-27845. This example and the link given in the example are working fine, but if I do the same with my url then I get the above error
I Hope kindly check your parsing issues may occurred.
#Override
public void onFailure(retrofit2.Call<Items> call, Throwable t) {
System.out.println("onFailure"+call);
//add this lije you got exceptions.
t.printStackTrace();
}
Change your Endpoints interface for this:
public interface Endpoints {
#POST("userregister/newuser")
#FormUrlEncoded
Call<Items> newuser(#Field("Data") String Data);
}
Note that I removed the trailing slash /. This way Retrofit appends the path you defined to the BASE_URL.
refer to the docs for Retrofit.Builder for a more detailed explanation, but pay particular attention to these bits:
Base URLs should always end in /.
A trailing / ensures that endpoints values which are relative paths
will correctly append themselves to a base which has path components.
...
Endpoint values which contain a leading / are absolute.
Absolute values retain only the host from baseUrl and ignore any
specified path components.
as presently written, the path referenced in your call to Endpoints.newuser() is absolute, and therefore the path segments after the host in your base URL are dropped (as this is the documented behavior).
therefore, you should change your Endpoints interface to use relative paths instead, like so:
public interface Endpoints {
#POST("userregister/newuser")
#FormUrlEncoded
Call<Items> newuser(#Field("Data") String Data);
}
I try to build a parametered middleware, but I only get http 504 error. This code works fine without the parameter
any idea?
public void Configuration(IAppBuilder app)
{
app.Use<MyMiddleware>("Hello");
}
class MyMiddleware : OwinMiddleware
{
public MyMiddleware(OwinMiddleware next, string message)
: base(next)
{
Message = message;
}
public string Message { get; set; }
public override async Task Invoke(IOwinContext context)
{
context.Response.ContentLength = Message.Length;
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(Message);
await Next.Invoke(context);
}
}
Ok I found the issue
ContentLength should be evaluated in Utf-8 like this:
Encoding.UTF8.GetBytes(Message).Length
c# uses utf-16 encoding by default