How to solve the cross domain in HtmlUnit - cross-domain

Error:
六月 21, 2016 4:15:06 下午 com.gargoylesoftware.htmlunit.xml.XmlPage <init>
警告: Failed parsing XML document http://live3.win007.com/vbsxml/goalBf3.xml?r=0071466496906000: Content is not allowed in prolog.
六月 21, 2016 4:15:06 下午 com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine handleJavaScriptException
信息: Caught script exception
======= EXCEPTION START ========
EcmaError: lineNumber=[41] column=[0] lineSource=[<no source>] name=[TypeError] sourceName=[http://live3.win007.com/common2.js] message=[TypeError: Cannot read property "childNodes" from null (http://live3.win007.com/common2.js#41)]
com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot read property "childNodes" from null (http://live3.win007.com/common2.js#41)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:865)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:628)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:747)
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadExternalJavaScriptFile(HtmlPage.java:1032)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:395)
at com.gargoylesoftware.htmlunit.html.HtmlScript$3.execute(HtmlScript.java:276)
common2.js code:
function getOddsData() {
oddsHttp.open("get", "vbsxml/goalBf3.xml?r=007" + Date.parse(new Date()), false);
oddsHttp.setRequestHeader("User-Agent", "");
oddsHttp.send(null);
var root = oddsHttp.responseXML.documentElement.childNodes[0];
oddsHttp as XMLHttpRequest
I suspect that a cross domain problem leads to " Cannot read property "childNodes""
I want to modify the JS by the following methods
public WebResponse getResponse(WebRequest request) throws IOException {
if(request.getUrl().toExternalForm().contains("common2.js")){
....
}
}
How to fix it?

This is not a cross domain problem,the warning: Content is not allowed in prolog is the key
I solved the problem by the following code
new WebConnectionWrapper(wc) {
public WebResponse getResponse(WebRequest request) throws IOException {
WebResponse response = super.getResponse(request);
if(request.getUrl().toExternalForm().contains("goalBf3.xml")){
System.out.println(response.getContentAsString("UTF-8"));
String content = response.getContentAsString("UTF-8");
if(null != content && !"".equals(content)){
if(content.indexOf("<") != -1 && content.lastIndexOf(">") != -1 && content.lastIndexOf(">") > content.indexOf("<"))
content = content.substring(content.indexOf("<"), content.lastIndexOf(">") + 1);
}
WebResponseData data = new WebResponseData(content.getBytes("UTF-8"),
response.getStatusCode(), response.getStatusMessage(), response.getResponseHeaders());
response = new WebResponse(data, request, response.getLoadTime());
}
return response;
}
}

Related

Primefaces Document Viewer Exception Handling

I am using Primefaces documentViewer from primefaces-extensions 12 as follows :
<pe:documentViewer zoom="page-fit" pagemode="thumbs"
id="iframeViewPdf" width="80%" height="800"
url="/pdfServlet?id=#{param.id}"/>
My controller writes the bytes to the response as follows :
#RequestMapping(value = "/pdfServlet")
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
// code here
try{
documentId = request.getParameter("id");
inputStream = myRepository.getFileAsInputStream(documentId);
outputStream = response.getOutputStream();
IOUtils.copy(inputStream, outputStream);
}catch(Exception e){
// all below didn't work
// request.getRequestDispatcher(request.getContextPath() + "/error").forward(request, response);
// response.sendRedirect(request.getContextPath() + "/error");
// throw e;
// what should be done here to redirect to error page / show error message in the page
}finally{
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
}
Above code works fine, but when any exception occurs in the backend I want to handle it in the client side, I tried to throw the exception in the catch part and got no effect.
Note: my application has error page configuration for any exception to forward to error page.
I also tried to redirect/forward to error page in the catch part, but I always gets an exception that cannot forward/redirect after response is committed.
How can I better handle exception in this case?
UPDATE : below is the response I get in the viewer when loading exception occurs in the backend, is there's any way to call a javascript function instead ?
I was able to handle the error using javascript interval on load as follows :
window.onload = function(){
PF('statusDialog').show();
var checkExist = setInterval(function() {
var iframe=document.getElementsByTagName('iframe')[0];
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var viewer = innerDoc.getElementById('viewer');
var errorMessage = innerDoc.getElementById('errorMessage');
var innerHTML = viewer.innerHTML;
if(innerHTML != null && innerHTML!='' && innerHTML!='undefined'){
clearInterval(checkExist);
PF('statusDialog').hide();
}
if(errorMessage != null && errorMessage.innerText != ''){
clearInterval(checkExist);
PF('statusDialog').hide();
// handle error here
window.location.href = getContextPath()+'/error';
}
}, 1000);
}
Why not put a custom Error in your web.xml???
web.xml
<!-- Handle Invalid PDF errors gracefully -->
<error-page>
<exception-type>com.your.InvalidPdfException</exception-type>
<location>/pages/error.xhtml</location>
</error-page>
Then in your code throw new InvalidPdfException().

Microsoft.WindowsAzure.Storage version : 9.3.2.0 - Microsoft.WindowsAzure.Storage.StorageException: Remote server returned an error: (403) Forbidden

I am using Microsoft.WindowsAzure.Storage (Azure Storage SDK for Windows) version : 9.3.2.0 for uploading the blob.
Here is logic of c# code for the same.
private class FileBlock
{
internal string Id { get; set; }
internal byte[] Content { get; set; }
}
public static async Task<Uri> UploadFileToAzureStorageAsync(string azureStorageUri, string filePath)
{
var bytes = File.ReadAllBytes(filePath);
var cloudBlockBlob = new CloudBlockBlob(new Uri(azureStorageUri));
var blocks = new HashSet<string>(); `enter code here`
try
{
foreach (var block in GetFileBlocks(bytes))
{
cloudBlockBlob.PutBlock(block.Id, new MemoryStream(block.Content, true), null);
blocks.Add(block.Id);
}
await cloudBlockBlob.PutBlockListAsync(blocks);
}
catch (Exception ex)
{
Logging.logger.Error(ex);
}
return cloudBlockBlob.Uri;
}
private static IEnumerable<FileBlock> GetFileBlocks(byte[] fileContent)
{
if (fileContent.Length == 0)
return new HashSet<FileBlock>();
var maxBlockSize = 4 * 1024 * 1024;
var hashSet = new HashSet<FileBlock>();
var blockId = 0;
var index = 0;
var currentBlockSize = maxBlockSize;
while (currentBlockSize == maxBlockSize)
{
if ((index + currentBlockSize) > fileContent.Length)
currentBlockSize = fileContent.Length - index;
var chunk = new byte[currentBlockSize];
Array.Copy(fileContent, index, chunk, 0, currentBlockSize);
hashSet.Add(new FileBlock
{
Content = chunk,
Id = Convert.ToBase64String(BitConverter.GetBytes(blockId))
});
index += currentBlockSize;
blockId++;
}
return hashSet;
}
I am seeing this issue intermittently for few packages. If i publish again it will be successful. I read few blogs which suggest to change machine to UTC time zone. I tried that as well but still the same error occurs as shown below.
I wanted to know if there is issue for the below exception.
Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (403) Forbidden.
---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
StatusMessage:Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
ErrorCode:AuthenticationFailed
ErrorMessage:Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
Thanks,
Sangamesh

Hazelcast failed to create an ObjectName when using file|http(s) protocol

after running on this exception using hazelcast 3.6 :
java.lang.IllegalArgumentException: Failed to create an ObjectName
at
com.hazelcast.jmx.HazelcastMBean.setObjectName(HazelcastMBean.java:116)
at
com.hazelcast.jmx.ConnectionManagerMBean.(ConnectionManagerMBean.java:39)
at
com.hazelcast.jmx.InstanceMBean.createMBeans(InstanceMBean.java:74)
at com.hazelcast.jmx.InstanceMBean.(InstanceMBean.java:67) at
com.hazelcast.jmx.ManagementService.(ManagementService.java:67)
at
com.hazelcast.instance.HazelcastInstanceImpl.(HazelcastInstanceImpl.java:136)
at
com.hazelcast.instance.HazelcastInstanceFactory.constructHazelcastInstance(HazelcastInstanceFactory.java:160)
at
com.hazelcast.instance.HazelcastInstanceFactory.getOrCreateHazelcastInstance(HazelcastInstanceFactory.java:98)
at
com.hazelcast.cache.impl.HazelcastServerCachingProvider.getOrCreateInstance(HazelcastServerCachingProvider.java:98)
at
com.hazelcast.cache.impl.HazelcastServerCachingProvider.createHazelcastCacheManager(HazelcastServerCachingProvider.java:64)
at
com.hazelcast.cache.impl.HazelcastServerCachingProvider.createHazelcastCacheManager(HazelcastServerCachingProvider.java:42)
at
com.hazelcast.cache.impl.AbstractHazelcastCachingProvider.getCacheManager(AbstractHazelcastCachingProvider.java:94)
at
com.hazelcast.cache.HazelcastCachingProvider.getCacheManager(HazelcastCachingProvider.java:131)
I took look at this part of the code, which is causing the error, on File: HazelcastServerCachingProvider.java (starting at line: 78 ):
String location = properties.getProperty(HazelcastCachingProvider.HAZELCAST_CONFIG_LOCATION);
// If config location is specified, get instance through it.
if (location != null) {
URI uri = new URI(location);
String scheme = uri.getScheme();
if (scheme == null) {
// It is a place holder
uri = new URI(System.getProperty(uri.getRawSchemeSpecificPart()));
}
ClassLoader theClassLoader = classLoader == null ? getDefaultClassLoader() : classLoader;
final URL configURL;
if ("classpath".equals(scheme)) {
configURL = theClassLoader.getResource(uri.getRawSchemeSpecificPart());
} else if ("file".equals(scheme) || "http".equals(scheme) || "https".equals(scheme)) {
configURL = uri.toURL();
} else {
throw new URISyntaxException(location, "Unsupported protocol in configuration location URL");
}
try {
Config config = new XmlConfigBuilder(configURL).build();
config.setClassLoader(theClassLoader);
**HERE BAD INSTANCENAME IS GENERATED**
config.setInstanceName(configURL.toString());
return HazelcastInstanceFactory.getOrCreateHazelcastInstance(config);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
When using file or http(s) protocol in the passed hazelcast_config_location, we are going to fail creating the mbean, since the hazelCastInstanceName should not contain the character ‘:’, which is unfortunately part of the configURI name.
Is this a Bug or do I overlooked something??
Thanks for your response
javax ObjectName class does not support the character : and throws a MalformedObjectNameException. Hazelcast processes this exception and throws IllegalArgumentException with the message comes from it.
https://github.com/hazelcast/hazelcast/blob/master/hazelcast/src/main/java/com/hazelcast/internal/jmx/HazelcastMBean.java#L121
https://docs.oracle.com/javase/7/docs/api/javax/management/ObjectName.html
Edit: quote function should've handled it in your case however, there is a bug in hz apparently. See: https://github.com/hazelcast/hazelcast/blob/master/hazelcast/src/main/java/com/hazelcast/internal/jmx/ConnectionManagerMBean.java#L38

classCastException in Mockito with Java.lang.String

I have the following piece of code for which I'm writing the unit test using Mockito
if (user != null) {
LDAPCustomer cust = getLDAPCustomer();
LDAPAuthorization auth = getLDAPAuthorization();
cust = getCustomerData( new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.CUSTOMER_MAIL, user));
if (cust != null)
auth = getAuthorizationData(new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.AUTHORIZATION_GUID, cust.getCstAuthGuid()));
if (cust != null && auth!= null && cust.getCstManageeGuids().size() == 1) {
String custGuid = cust.getCstCustGuid();
if (cust.getCstManageeGuids().get(0).equals(custGuid)) {
//No secondary user
try
{
deleteUserAssociations(cust.getCstCustGuid());
resetAuthorization(auth.getCstAuthGuid());
logger.info(cust.getCstCustGuid()+" user successfully perged.");
} catch (Exception e) {
logger.error("Error occured whie try to purging user: "+MiscUtility.getStackTrace(e));
throw new Exception("Error occured whie try to purging user: "+e.getMessage());
}
}
}
}
and here's the mockito code
int size = 1;
//Define the Stub
Mockito.doReturn(mockCustomer).when(ldap).getLDAPCustomer();
Mockito.doReturn(mockAuthorization).when(ldap).getLDAPAuthorization();
Mockito.doReturn(mockCustomer).when(ldap).getCustomerData(Mockito.any(LDAPInterface.LDAPInstruction.class));
Mockito.doReturn(mockAuthorization).when(ldap).getAuthorizationData(Mockito.any(LDAPInterface.LDAPInstruction.class));
Mockito.when(mockCustomer.getCstManageeGuids().size()).thenReturn(size);
Mockito.when(mockCustomer.getCstCustGuid()).thenReturn("mockCust");
Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);
Mockito.doNothing().when(ldap).deleteUserAssociations(Mockito.anyString());
Mockito.doNothing().when(ldap).resetAuthorization(Mockito.anyString());
I'm getting a ClassCastException as below
java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$1ebf8eb1 cannot be cast to java.lang.String
at the line
Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);
Appreciate any help.
Solved it by breaking down the chain.
List<String> lst = new ArrayList<String>();
lst.add("mockVal");
Mockito.when(mockCustomer.getCstManageeGuids()).thenReturn(lst);

groovy HTTP Builder not returning results

I have the following code in groovy
HTTPBuilder http = new HTTPBuilder("https://ronna-afghan.harmonieweb.org/_layouts/searchrss.aspx")
http.request(Method.GET, groovyx.net.http.ContentType.XML) {
// set username and password for basic authentication
// set username and password for basic auth
//http.auth.basic(ConfigurationHolder.config.passportService.userName,
// ConfigurationHolder.config.passportService.password)
headers.'User-Agent' = 'Mozilla/5.0'
uri.query = [k:'execution']
// response handler for a success response code:
response.success = {resp, xml ->
println resp.statusLine
log.debug "response status: ${resp.statusLine}"
log.debug xml.toString()
}
// handler for any failure status code:
response.failure = {resp ->
log.error " ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
when I run the code, it doesn't give me the rss feed which I'm suppose to get
When I have the same code in java
try {
// Create a URLConnection object for a URL
URL oracle = new URL(
"https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
it returns the xml Rss. I can't figure what the issue might be. Everything looks okay to me in the groovy code and also the Http return code is 200.
The code that you have described in Java is the equivalent of the following code in Groovy:
def oracle = "https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss".toURL().text

Resources