Inheritance security rules violated while overriding member in Silverlight - silverlight

I am working on a web application in silverlight. I have overloaded the WebClient.GetWebRequest method as given below:-
public class WebClientWithCookies : WebClient
{
[SecurityCritical]
protected override WebRequest GetWebRequest(Uri address)
{
string cookieContent = HtmlPage.Document.Cookies;
WebRequest request = base.GetWebRequest(address);
HttpWebRequest webRequest = request as HttpWebRequest;
if (webRequest != null && cookieContent != null && cookieContent != string.Empty)
{
CookieContainer cookieContainer = new CookieContainer();
cookieContainer.Add(address, new Cookie() { Value = HtmlPage.Document.Cookies });
webRequest.CookieContainer = cookieContainer;
}
return request;
}
}
But I am getting the following exception:
System.TypeInitializationException was unhandled by user code
Message=The type initializer for 'SigmaWC.Utility.RestCommunicator'
threw an exception. TypeName=SigmaWC.Utility.RestCommunicator
StackTrace:
at SigmaWC.Utility.RestCommunicator..ctor()
at SigmaWC.App..ctor() InnerException: System.TypeLoadException
Message=Inheritance security rules violated while overriding member: 'SigmaWC.Utility.WebClientWithCookies..ctor()'. Security
accessibility of the overriding method must match the security
accessibility of the method being overriden.
StackTrace:
at SigmaWC.Utility.RestCommunicator..cctor()
InnerException:
Can anyone help in how to elevate the security settings in silverlight.

Documentation about this is scarce to say the least. However, there are a couple of resources which are useful:
MSDN Indicates that you cannot use framework members with a SecurityCriticalAttribute.
Types and members that have the SecurityCriticalAttribute cannot be used by Silverlight application code. Security-critical types and members can be used only by trusted code in the .NET Framework for Silverlight class library.
In the case of WebClient, the GetWebRequest method does not have this attribute, however the constructor does.
This MSDN Security blog Implies that if the default constructor has any Security attribute, the class cannot be used for inheritance in a Silverlight client.
Further to that, the aforementioned MSDN blog implies that Security attributes are ignored in Silverlight assemblies which are not part of the core framework. This may however only apply to Assembly level attributes.
Anyway, to cut a long story short. You cannot derive from WebClient because of the SecuritySafeAttribute on the constructor.
To illustrate the point, this also causes an exception at runtime:
public class MyWebClient : WebClient
{
}
The alternative is to roll your own WebClient. It takes a little work, but the following example does work with the following handler:
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
foreach (Cookie cookie in context.Response.Cookies)
{
//Cookies from the client - there will be 1 in this case
}
}
...
public class MyWebClient
{
public MyWebClient()
{
}
public void InvokeWebRequest(Uri address)
{
//Set the cookie you want to use.
string cookieContent = "I like cookies";
// Register a http client - without this the following webRequest.CookieContainer setter will throw an exception
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
//This bit you know, but dont forget to set Name on your new Cookie.
HttpWebRequest webRequest = WebRequest.Create(address.AbsoluteUri) as HttpWebRequest;
if (webRequest != null && !String.IsNullOrWhiteSpace(cookieContent))
{
webRequest.CookieContainer = new CookieContainer();
webRequest.CookieContainer.Add(address, new Cookie() { Value = cookieContent, Name = "MyCookie" });
}
//Invoke the async GetResponse method.
webRequest.BeginGetResponse(o =>
{
HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(o);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
//Read the result
string result = reader.ReadToEnd();
}
foreach (Cookie cookie in response.Cookies)
{
//The cookies returned from the server.
}
}, null);
}
}

Related

#AfterReturning from ExceptionHandler not working

I have a GlobalExceptionHandler class which contain multiple methods annotated with #ExceptionHandler.
#ExceptionHandler({ AccessDeniedException.class })
public final ResponseEntity<Object> handleAccessDeniedException(
Exception ex, WebRequest request) {
return new ResponseEntity<Object>(
"Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN);
}
I have a AOP which is suppose to be triggered after the exception handler returns response.
#AfterReturning(value="#annotation(exceptionHandler)",returning="response")
public void afterReturningAdvice(JoinPoint joinPoint, Object response) {
//do something
}
But the #AfterReturning is not triggered after the handler returns a valid response.
Tried full qualified name but not working
#AfterReturning(value = "#annotation(org.springframework.web.bind.annotation.ExceptionHandler)", returning = "response"){
public void afterReturningAdvice(JoinPoint joinPoint, Object response) {
//do something
}
Please go through the documentation to understand the proxying mechanisms in Spring framework.
Assuming the ExceptionHandler code written was of the following format
#ControllerAdvice
public class TestControllerAdvice {
#ExceptionHandler({ AccessDeniedException.class })
final public ResponseEntity<Object> handleAccessDeniedException(
Exception ex, WebRequest request) {
return new ResponseEntity<Object>(
"Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN);
}
}
key points from the documentation pertaining to the question are
Spring AOP uses either JDK dynamic proxies or CGLIB to create the
proxy for a given target object.
If the target object to be proxied implements at least one
interface, a JDK dynamic proxy is used. All of the interfaces
implemented by the target type are proxied. If the target object
does not implement any interfaces, a CGLIB proxy is created.
With CGLIB, final methods cannot be advised, as they cannot be overridden in runtime-generated subclasses.
OP identified the issue based on the comments and hints , this answer is for any future references.

Hystrix Javanica : Call always returning result from fallback method.(java web app without spring)

I am trying to integrate Hystrix javanica into my existing java EJB web application and facing 2 issues with running it.
When I try to invoke following service it always returns response from fallback method and I see that the Throwable object in fallback method has "com.netflix.hystrix.exception.HystrixTimeoutException" exception.
Each time this service is triggered, HystrixCommad and fallback methods are called multiple times around 50 times.
Can anyone suggest me with any inputs? Am I missing any configuration?
I am including following libraries in my project.
project libraries
I have setup my aspect file as follows:
<aspectj>
<weaver options="-verbose -showWeaveInfo"></weaver>
<aspects>
<aspect name="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>
</aspects>
</aspectj>
Here is my config.properties file in META-INF/config.properties
hystrix.command.default.execution.timeout.enabled=false
Here is my rest service file
#Path("/hystrix")
public class HystrixService {
#GET
#Path("clusterName")
#Produces({ MediaType.APPLICATION_JSON })
public Response getClusterName(#QueryParam("id") int id) {
ClusterCmdBean clusterCmdBean = new ClusterCmdBean();
String result = clusterCmdBean.getClusterNameForId(id);
return Response.ok(result).build();
}
}
Here is my bean class
public class ClusterCmdBean {
#HystrixCommand(groupKey = "ClusterCmdBeanGroup", commandKey = "getClusterNameForId", fallbackMethod = "defaultClusterName")
public String getClusterNameForId(int id) {
if (id > 0) {
return "cluster"+id;
} else {
throw new RuntimeException("command failed");
}
}
public String defaultClusterName(int id, Throwable e) {
return "No cluster - returned from fallback:" + e.getMessage();
}
}
Thanks for the help.
If you want to ensure you are setting the property, you can do that explicitly in the circuit annotation itself:
#HystrixCommand(commandProperties = {
#HystrixProperty(name = "execution.timeout.enabled", value = "false")
})
I would only recommend this for debugging purposes though.
Something that jumps out to me is that Javanica uses AspectJ AOP, which I have never seen work with new MyBean() before. I've always have to use #Autowired with Spring or similar to allow proxying. This could well just be something that is new to me though.
If you set a breakpoint inside the getClusterNameForId can you see in the stack trace that its being called via reflection (which it should be AFAIK)?
Note you can remove commandKey as this will default to the method name. Personally I would also remove groupKey and let it default to the class name.

Spring rest application and exception localization

I am developing a spring boot app with restful services and angularjs as front end. The application must support multiple languages. One of the things I am having problem is the business exceptions thrown from my services. E.g. I have a book service which may throw an exception like this
if (book == null) {
throw new ServiceException("The book you are looking for no longer exist");
}
What is the best approach to localize them?
You have to use #RestControllerAdvice to seprate your exception handling logic from your business code. As per #ControllerAdvice doc, the methods defined in the class annotated as #ControllerAdvice apply globally to all Controllers. #RestControllerAdvice is just a convenience class equal to (#RestControllerAdvice = #ControllerAdvice + #ResponseBody). Please check below class:
#RestControllerAdvice
public class GenericExceptionHandler {
#Autowired
private MessageSource messageSource;
#ExceptionHandler(ServiceException.class)
public ResponseEntity<ErrorResponse> handle(ServiceException.class e, Locale locale) {
String errorMessage = messageSource.getMessage(
"error.message", new Object[]{},locale);
ErrorResponse error = new ErrorResponse();
error.setErrorCode(HttpStatus.BAD_REQUEST.value());
error.setMessage(errorMessage);
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
}
// other Custom Exception handlers
Your ErrorResponse is normal javabean as below:
public class ErrorResponse{
private int errorCode;
private String message;
//getter and setter
}
And you should have MessageSource configured in your configuration to read the locale specific error messages as below:
#Configuration
public class MessageConfig {
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("i18n/messages");
source.setUseCodeAsDefaultMessage(true);
return source;
}
}
I would like to suggest use of #ControllerAdvice and #ExceptionHandler.
Also you can use #RestControllerAdvice, find example here

Timeout waiting for connection from pool - despite single SolrServer

We are having problems with our solrServer client's connection pool running out of connections in no time, even when using a pool of several hundred (we've tried 1024, just for good measure).
From what I've read, the following exception can be caused by not using a singleton HttpSolrServer object. However, see our XML config below, as well:
Caused by: org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
at org.apache.http.impl.conn.PoolingClientConnectionManager.leaseConnection(PoolingClientConnectionManager.java:232)
at org.apache.http.impl.conn.PoolingClientConnectionManager$1.getConnection(PoolingClientConnectionManager.java:199)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:455)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at org.apache.solr.client.solrj.impl.HttpSolrServer.executeMethod(HttpSolrServer.java:448)
XML Config:
<solr:solr-server id="solrServer" url="http://solr.url.domain/"/>
<solr:repositories base-package="de.ourpackage.data.solr" multicore-support="true"/>
At this point, we are at a loss. We are running a web application on a tomcat7. Whenever a user requests a new website, we send one or more request to the Solr Server, requesting whatever we need, which are usually single entries or page of 20 (using Spring Data).
As for the rest of our implementation, we are using an abstract SolrOperationsrepository class, which is extended by each of our repositories (one repository for each core).
The following is how we set our solrServer. I suspect we are doing something fundamentally wrong here, which is why our connections are overflowing. According to the logs, they are always being returned into the pool, btw.
private SolrOperations solrOperations;
#SuppressWarnings("unchecked")
public final Class<T> getEntityClass() {
return (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public final SolrOperations getSolrOperations() {
/*HttpSolrServer solrServer = (HttpSolrServer)solrOperations.getSolrServer();
solrServer.getHttpClient().getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS);*/
logger.info("solrOperations: " + solrOperations);
return solrOperations;
}
#Autowired
public final void setSolrServer(SolrServer solrServer) {
try {
String core = SolrServerUtils.resolveSolrCoreName(getEntityClass());
SolrTemplate template = templateHolder.get(core);
/*solrServer.setConnectionTimeout(500);
solrServer.setMaxTotalConnections(2048);
solrServer.setDefaultMaxConnectionsPerHost(2048);
solrServer.getHttpClient().getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS);*/
if ( template == null ) {
template = new SolrTemplate(new MulticoreSolrServerFactory(solrServer));
template.setSolrCore(core);
template.afterPropertiesSet();
logger.debug("Creating new SolrTemplate for core '" + core + "'");
templateHolder.put(core, template);
}
logger.debug("setting SolrServer " + template);
this.solrOperations = template;
} catch (Exception e) {
logger.error("cannot set solrServer...", e);
}
}
The code that is commented out has been mostly used for testing purposes. I also read somewhere else that you cannot manipulate the solrServer object on-the-fly. Which begs the question, how do I set a timeout/poolsize in the XML config?
The implementation of a repository looks like this:
#Repository(value="stellenanzeigenSolrRepository")
public class StellenanzeigenSolrRepositoryImpl extends SolrOperationsRepository<Stellenanzeige> implements StellenanzeigenSolrRepositoryCustom {
...
public Query createQuery(Criteria criteria, Sort sort, Pageable pageable) {
Query resultQuery = new SimpleQuery(criteria);
if ( pageable != null ) resultQuery.setPageRequest(pageable);
if ( sort != null ) resultQuery.addSort(sort);
return resultQuery;
}
public Page<Stellenanzeige> findBySearchtext(String searchtext, Pageable pageable) {
Criteria searchtextCriteria = createSearchtextCriteria(searchtext);
Query query = createQuery(searchtextCriteria, null, pageable);
return getSolrOperations().queryForPage(query, getEntityClass());
}
...
}
Can any of you point to mistakes that we've made, that could possibly lead to this issue? Like I said, we are at a loss. Thanks in advance, and I will, of course update the question as we make progress or you request more information.
The MulticoreServerFactory always returns an object of HttpClient, that only ever allows 2 concurrent connections to the same host, thus causing the above problem.
This seems to be a bug with spring-data-solr that can be worked around by creating a custom factory and overriding a few methods.
Edit: The clone method in MultiCoreSolrServerFactory is broken. This hasn't been corrected yet. As some of my colleagues have run into this issue recently, I will post a workaround here - create your own class and override one method.
public class CustomMulticoreSolrServerFactory extends MulticoreSolrServerFactory {
public CustomMulticoreSolrServerFactory(final SolrServer solrServer) {
super(solrServer);
}
#Override
protected SolrServer createServerForCore(final SolrServer reference, final String core) {
// There is a bug in the original SolrServerUtils.cloneHttpSolrServer()
// method
// that doesn't clone the ConnectionManager and always returns the
// default
// PoolingClientConnectionManager with a maximum of 2 connections per
// host
if (StringUtils.hasText(core) && reference instanceof HttpSolrServer) {
HttpClient client = ((HttpSolrServer) reference).getHttpClient();
String baseURL = ((HttpSolrServer) reference).getBaseURL();
baseURL = SolrServerUtils.appendCoreToBaseUrl(baseURL, core);
return new HttpSolrServer(baseURL, client);
}
return reference;
}
}

Silverlight Enabled WCF Service Exception Handling

I've got a Silverlight enabled WCF web service set up and I'm connecting to it from my Silverlight application.
The Service is not written using the ASync pattern but Silverlight generates the async methods automatically.
I have a method that within my service that has a chance of throwing an exception I can catch this exception but I'm not sure of the best way of handling this exception, I've noticed that the event args of the completed method contain an error property.
Is is possible to set the value of this error property?
Example Method
public class service
{
[OperationContract]
public Stream getData(string filename)
{
string filepath = HostingEnvironment.MapPath(filename);
FileInfo fi = new FileInfo(filenpath);
try
{
Stream s = fi.Open(FileMode.Open);
return s;
}
catch (IOException e)
{
return null;
}
}
}
Silverlight Code
btnFoo_Click(object sender, RoutedEventArgs e)
{
ServiceClient svc = new ServiceClient();
svc.getDataCompleted += new EventHandler<getDataCompletedEventArgs>(getData_Completed);
svc.getDataAsync("text.txt");
}
void getData_Completed(object sender, getDataCompletedEventArgs e)
{
e.Error //how can i set this value on the service?
}
Finally if the service is offline or times out is there anyway to catch this exception before it reaches the UnhandledException method within App.xaml?
Thanks
Since silverlight is using services asyncronously you dont get a synchronous exception throw, but instead it is stored in e.Error property, that you need to check in your ServiceCallCompleted method.
To answer your question
how can i set this value on the service?
Simply throw an exception on server and it can be enough given several other conditions.
You may want to introduce FaultContract on your WCF service method, and throw FaultException<T> which is a common way to deal with errors in WCF.
However fault result in return code 500 and silverlight won't be able to get response with such status code and have access to Fault object, even if you add that attribute to service.
This can be solved using several approaches.
Use the alternative client HTTP stack: You can register an alternative HTTP stack by using the RegisterPrefix method. See below for an outline of how to do this. Silverlight 4 provides the option of using a client HTTP stack which, unlike the default browser HTTP stack, allows you to process SOAP-compliant fault messages. However, a potential problem of switching to the alternative HTTP stack is that information stored by the browser (such as authentication cookies) will no longer be available to Silverlight, and thus certain scenarios involving secure services might stop working, or require additional code to work.
Modify the HTTP status code: You can modify your service to return SOAP faults with an HTTP status code of 200, Silverlight 4 so that faults will be processed successfully. How to do this is outlined below. Note that this will make the service non-compliant with the SOAP protocol, because SOAP requires a response code in the 400 or 500 range for faults. If the service is a WCF service, you can create an endpoint behavior that plugs in a message inspector that changes the status code to 200. Then you can create an endpoint specifically for Silverlight consumption, and apply the behavior there. Your other endpoints will still remain SOAP-compliant.
Faults in silverlight
Creating and Handling Faults in Silverlight
OR
[DataContract]
public class MyError
{
[DataMember]
public string Code { get; set; }
[DataMember]
public string Message { get; set; }
[DataMember]
public DateTime Time { get; set; }
}
public class service
{
[OperationContract]
public Stream getData(string filename, out MyError myError)
{
myError = null;
string filepath = HostingEnvironment.MapPath(filename);
FileInfo fi = new FileInfo(filenpath);
try
{
Stream s = fi.Open(FileMode.Open);
return s;
}
catch (IOException e)
{
myError = new MyError() { Code = "000", Message = ex.Message, Time = DateTime.Now };
return null;
}
}
}
I wish successful projects

Resources