I'm trying to add a picture to my pdf-file withe the fo:external-graphic-tag:
<fo:external-graphic src="url(resources\common\img\Logo_tiny.png)" />
On my local System everyting works fine, but when i want to run it on the Server-System it says
Image not found. URI: resources\common\img\Logo_tiny.png. (No context info available)
My Fop-Factory-Setup looks like this:
fopFactory.setUserConfig(config);
fopFactory.getFontManager().setFontBaseURL(servletContext.getRealPath("/WEB-INF/config/"));
Fop fop = fopFactory.newFop(org.apache.xmlgraphics.util.MimeConstants.MIME_PDF, userAgent, outStream);
Transformer transformer = TransformerFactory.newInstance().newTransformer(transformSource);
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(source, res);
// get the pdf:
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"Output.pdf\"");
response.setContentLength(outStream.size());
OutputStream responseOutputStream = response.getOutputStream();
outStream.writeTo(responseOutputStream);
responseOutputStream.flush();
responseOutputStream.close();
context.responseComplete();
I checked everything a couple of times: the image is available in the jar-file it is available in the ear-file. The picture is also used in a different context nd there it shows up.
Does anyone have a hint or a solution for this problem?
Many Thanks!!
Related
I am using epubreader (vers-one) NuGet package for parsing .epub files.
My Code:
string fileName = "SampleEPUB.epub";
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{fileName}");
EpubBook epubBook = EpubReader.ReadBook(stream);
foreach (EpubNavigationItem chapter in epubBook.Navigation)
{
chapterDetails.Add(new ChapterDetails() { title = chapter.Title, htmlData = chapter.HtmlContentFile?.Content, subChapters = chapter.NestedItems });
}
For testing purposes, I have added the epub files on the project and parse the chapters like above. I need to change this implementation.
I am able to get the epub file links stored in our database. Now I need to parse the chapters of epub from the link. But when I use the link as the fileName in the above code I am getting the below exception:
System.AggregateException: 'One or more errors occurred. (Value cannot be null.Parameter name: stream)'
How can I solve this issue? One sample link is here. I have added a sample project here having .epub file links for the reference (epub file links are commented in the sample).
System.AggregateException: 'One or more errors occurred. (Value cannot be null.Parameter name: stream)'
The GetManifestResourceStream method is used to access the embedded file which should be placed in shared project for the Xamarin.Forms project. The code doesn't works for the file comes from a database. You could debug to get that the stream is null because the fileName doesn't exist in the project.
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{fileName}");
In your condition, it just needs to get the stream from the url. Try to use the following code to get the stream.
Stream stream;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)aRequest.GetResponse();
stream = response.GetResponseStream();
As the title says.
I set the values in java like this:
response.setHeader("Content-Disposition", "attachment; filename=" + targetName);
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
I debugged in chrome explorer, and the response body is:
Question solved by changing the submit method in JS file.
At first I send request by this:
Ext.Ajax.request({
utl:'',
params:{},
method:'POST'
});
Butajax can't download a file but can receive json/html/js/string format body.
So in extjs, if you want to download file, DO NOT USE ajax request.
And maybe you'll need use native javascript to do it.
For example:
var form = document.createElement("form);
form.method='POST';
form.action='/';
//deal with data
document.body.appendChild(form);
form.submit();
I'm attempting to set the request header 'Referer' to spoof a request coming from another site. We need the ability test that a specific referrer is used, which returns a specific form to the user, otherwise an alternative form is given.
I can do this within poltergeist by:
page.driver.headers = {"Referer" => referer_string}
but I can't find the equivalent functionality for the selemium driver.
How can I set request headers in the capybara selenium driver?
Webdriver doesn't contain an API to do it. See issue 141 from Selenium tracker for more info. The title of the issue says that it's about response headers but it was decided that Selenium won't contain API for request headers in scope of this issue. Several issues about adding API to set request headers have been marked as duplicates: first, second, third.
Here are a couple of possibilities that I can propose:
Use another driver/library instead of selenium
Write a browser-specific plugin (or find an existing one) that allows you to add header for request.
Use browsermob-proxy or some other proxy.
I'd go with option 3 in most of cases. It's not hard.
Note that Ghostdriver has an API for it but it's not supported by other drivers.
For those people using Python, you may consider using Selenium Wire which can set request headers as well as provide you with the ability to inspect requests and responses.
from seleniumwire import webdriver # Import from seleniumwire
# Create a new instance of the Chrome driver (or Firefox)
driver = webdriver.Chrome()
# Create a request interceptor
def interceptor(request):
del request.headers['Referer'] # Delete the header first
request.headers['Referer'] = 'some_referer'
# Set the interceptor on the driver
driver.request_interceptor = interceptor
# All requests will now use 'some_referer' for the referer
driver.get('https://mysite')
Install with:
pip install selenium-wire
I had the same issue. I solved it downloading modify-headers firefox add-on and activate it with selenium.
The code in python is the following
fp = webdriver.FirefoxProfile()
path_modify_header = 'C:/xxxxxxx/modify_headers-0.7.1.1-fx.xpi'
fp.add_extension(path_modify_header)
fp.set_preference("modifyheaders.headers.count", 1)
fp.set_preference("modifyheaders.headers.action0", "Add")
fp.set_preference("modifyheaders.headers.name0", "Name_of_header") # Set here the name of the header
fp.set_preference("modifyheaders.headers.value0", "value_of_header") # Set here the value of the header
fp.set_preference("modifyheaders.headers.enabled0", True)
fp.set_preference("modifyheaders.config.active", True)
fp.set_preference("modifyheaders.config.alwaysOn", True)
driver = webdriver.Firefox(firefox_profile=fp)
Had the same issue today, except that I needed to set different referer per test. I ended up using a middleware and a class to pass headers to it. Thought I'd share (or maybe there's a cleaner solution?):
lib/request_headers.rb:
class CustomHeadersHelper
cattr_accessor :headers
end
class RequestHeaders
def initialize(app, helper = nil)
#app, #helper = app, helper
end
def call(env)
if #helper
headers = #helper.headers
if headers.is_a?(Hash)
headers.each do |k,v|
env["HTTP_#{k.upcase.gsub("-", "_")}"] = v
end
end
end
#app.call(env)
end
end
config/initializers/middleware.rb
require 'request_headers'
if %w(test cucumber).include?(Rails.env)
Rails.application.config.middleware.insert_before Rack::Lock, "RequestHeaders", CustomHeadersHelper
end
spec/support/capybara_headers.rb
require 'request_headers'
module CapybaraHeaderHelpers
shared_context "navigating within the site" do
before(:each) { add_headers("Referer" => Capybara.app_host + "/") }
end
def add_headers(custom_headers)
if Capybara.current_driver == :rack_test
custom_headers.each do |name, value|
page.driver.browser.header(name, value)
end
else
CustomHeadersHelper.headers = custom_headers
end
end
end
spec/spec_helper.rb
...
config.include CapybaraHeaderHelpers
Then I can include the shared context wherever I need, or pass different headers in another before block. I haven't tested it with anything other than Selenium and RackTest, but it should be transparent, as header injection is done before the request actually hits the application.
I wanted something a bit slimmer for RSpec/Ruby so that the custom code only had to live in one place. Here's my solution:
/spec/support/selenium.rb
...
RSpec.configure do |config|
config.after(:suite) do
$custom_headers = nil
end
end
module RequestWithExtraHeaders
def headers
$custom_headers.each do |key, value|
self.set_header "HTTP_#{key}", value
end if $custom_headers
super
end
end
class ActionDispatch::Request
prepend RequestWithExtraHeaders
end
Then in my specs:
/specs/features/something_spec.rb
...
$custom_headers = {"Referer" => referer_string}
If you are using javacsript and only want to implement on chrome, Puppeteer is the best option as it has native support to modify headers.
Check this out: https://pptr.dev/#?product=Puppeteer&version=v10.1.0&show=api-pagesetextrahttpheadersheaders
Although for cross-browser usage you might check out #requestly/selenium npm package. It is a wrapper around requestly extension to enable easy integration in selenium-webdriver.The extension can modify headers.
Check out: https://www.npmjs.com/package/#requestly/selenium
Setting request headers in the web driver directly does not work. This is true.
However, you can work around this problem by using the browser devtools (I tested with edge & chrome) and this works perfectly.
According to the documentation, you have the possibility to add custom headers:
https://chromedevtools.github.io/devtools-protocol/tot/Network/
Please find below an example.
[Test]
public async Task AuthenticatedRequest()
{
await LogMessage("=== starting the test ===");
EdgeOptions options = new EdgeOptions {UseChromium = true};
options.AddArgument("no-sandbox");
var driver = new RemoteWebDriver(new Uri(_testsSettings.GridUrl), options.ToCapabilities(), TimeSpan.FromMinutes(3));
//Get DevTools
IDevTools devTools = driver;
//DevTools Session
var session = devTools.GetDevToolsSession();
var devToolsSession = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
await devToolsSession.Network.Enable(new Network.EnableCommandSettings());
var extraHeader = new Network.Headers();
var data = await Base64KerberosTicket();
var headerValue = $"Negotiate {data}";
await LogMessage($"header values is {headerValue}");
extraHeader.Add("Authorization", headerValue);
await devToolsSession.Network.SetExtraHTTPHeaders(new Network.SetExtraHTTPHeadersCommandSettings
{
Headers = extraHeader
});
driver.Url = _testsSettings.TestUrl;
driver.Navigate();
driver.Quit();
await LogMessage("=== ending the test ===");
}
This is an example written in C# but the same shall probably work with java, python as well as the major platforms.
Hope it helps the community.
If you use the HtmlUnitDriver, you can set request headers by modifying the WebClient, like so:
final case class Header(name: String, value: String)
final class HtmlUnitDriverWithHeaders(headers: Seq[Header]) extends HtmlUnitDriver {
super.modifyWebClient {
val client = super.getWebClient
headers.foreach(h => client.addRequestHeader(h.name, h.value))
client
}
}
The headers will then be on all requests made by the web browser.
With the solutions already discussed above the most reliable one is using Browsermob-Proxy
But while working with the remote grid machine, Browsermob-proxy isn't really helpful.
This is how I fixed the problem in my case. Hopefully, might be helpful for anyone with a similar setup.
Add the ModHeader extension to the chrome browser
How to download the Modheader? Link
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(C://Downloads//modheader//modheader.crx));
// Set the Desired capabilities
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
// Instantiate the chrome driver with capabilities
WebDriver driver = new RemoteWebDriver(new URL(YOUR_HUB_URL), options);
Go to the browser extensions and capture the Local Storage context ID of the ModHeader
Navigate to the URL of the ModHeader to set the Local Storage Context
.
// set the context on the extension so the localStorage can be accessed
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/_generated_background_page.html");
Where `idgpnmonknjnojddfkpgkljpfnnfcklj` is the value captured from the Step# 2
Now add the headers to the request using Javascript
.
((Javascript)driver).executeScript(
"localStorage.setItem('profiles', JSON.stringify([{ title: 'Selenium', hideComment: true, appendMode: '',
headers: [
{enabled: true, name: 'token-1', value: 'value-1', comment: ''},
{enabled: true, name: 'token-2', value: 'value-2', comment: ''}
],
respHeaders: [],
filters: []
}]));");
Where token-1, value-1, token-2, value-2 are the request headers and values that are to be added.
Now navigate to the required web-application.
driver.get("your-desired-website");
You can do it with PhantomJSDriver.
PhantomJSDriver pd = ((PhantomJSDriver) ((WebDriverFacade) getDriver()).getProxiedDriver());
pd.executePhantomJS(
"this.onResourceRequested = function(request, net) {" +
" net.setHeader('header-name', 'header-value')" +
"};");
Using the request object, you can filter also so the header won't be set for every request.
If you just need to set the User-Agent header, there is an option for Chrome:
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"')
Now the browser sends User-Agent.
I am writing a Java Program which could be able to send SMS using Kannel. I have Configured Kannel in my VM Vare Virtual Machine (Red Hat). Kannel is working fine and I can send SMS by typing the url
http://192.168.214.128:13013/cgi-bin/sendsms?
username=tester&password=foobar&to=03478847037&text=Mahtab
in my Windows browser. But when I access the same URL through Java Program
I am getting this exception
java.io.IOException: Server returned HTTP response code: 400` for URL:
http://192.168.214.128:13013/cgi-bin/sendsms?
username=tester&password=foobar&to=03478847037&text=Mahtab
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245)
But when I paste the same url string in browser I am able to send the SMS.
code is attached
URL url = new URL("http://192.168.214.128:13013/cgi-bin/sendsms?username=tester&password=foobar&to=03478847037&text=Mahtab");
System.out.println(param.toString());
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {answer.append(line);}
writer.close();
reader.close();
System.out.println(answer.toString());
Now please help me in this regard what I am missing???
I have solved this problem ............ actually code and every thing was right. The only problem was Netbeans. I had not cleaned the project when made some changes ...... that's why it was not giving the desired outcome ..... I cleaned the project and then build it... and I was successful so lesson learnt is that some time you are logically true but unfortunately your IDE is doing a little error which teases you the most.. #thor thanks for helping
I have a flex app that uploads files to a server. The server requires authentication to be able to upload. In IE the upload works fine. However in FF and Safari, it does not upload. I have seen people all over with this same problem but no answers. Don't fail me now stackoverflowers.
I found this question while trying to find the answer myself. The solution was rather simple.
Based on the flash player bug that others have linked, and the comments on that page, I decided to append session identifiers to my upload URL and give it a shot. It really was that easy!
To make it work, I started by adding a flashVar parameter called sessionParams. This allowed me to pass any string I want in to the flash player as my session identifier, and it will later get appended to the URL used to upload.
//sessionParams - resolves firefox upload bug
public var sessionParams:String = "";
//...
public function initApp():void{
sessionParams = Application.application.parameters.sessionParams;
}
In my case, I'm on ColdFusion with java sessions enabled, so my sessionParams are setup like the following before being passed into the flash player:
<cfset flashVars = "sessionParams=#urlEncodedFormat('jsessionid=' & session.sessionid)#" />
Don't forget to escape special characters like =,&, etc (which I've done with urlEncodedFormat), so that they are treated as part of the value of the "sessionParams" parameter, and not breakpoints to indicate other parameters. You're embedding future-URL information in the current URL.
Then, use the sessionParams value in your upload code. Here's a snippet of how I set mine up:
// Set Up URLRequest
_uploadURL = new URLRequest;
_uploadURL.url = _url + "?" + _sessionParams;
_uploadURL.method = "GET";
_uploadURL.data = _variables;
_uploadURL.contentType = "multipart/form-data";
The variable names are different (but similar) because this is part of a reusable class.
Hopefully that helps you. If not, let me know and I'll try to provide more code or explanation to help you out.
The problem at least in Firefox is that the session cookies are not sent in the request when you invoke FileReference.upload(). What you need to do is add the authentication token either as a form variable or in the query string. Here is an example in Java where the session cookie is called "jsessionid"
var request : URLRequset = new URLRequest( uploadUrl + ";jsessionid=" + jsessionid);
You can parse the jsessionid out of cookies using Javascript and ExternalInterface to invoke the Javascript function. Or after you authenticate you can have Flex call a backend method that returns the current sessionID.
The related Flex bug is here:
http://bugs.adobe.com/jira/browse/FP-201
I solved this problem. File upload using flex will work on all the browsers.In J2ee application,
comment the security-constraint or make the fileupload.do URL unprotected in web.xml where you will put the actual code.
<security-constraint>
<display-name>Senusion Security Constraint</display-name>
<web-resource-collection>
<web-resource-name>Un Protected Area</web-resource-name>
<url-pattern>/fileupload.do</url-pattern>
</web-resource-collection>
</security-constraint>
Hope this will help the next reader.
FlashPlayer 10 provides a new Filereference API that can help a lot.
Here is a blog entry that describes it : http://www.flexpasta.com/index.php/2010/02/21/uploading-files-with-firefox-solution/.
Indeed in Flash 10 an enhancement to flash.net.FileReference makes it possible to read the contents of a file before it is uploaded. Meaning that the file can be uploaded in different ways then can be done in Flash 9. The following example shows how easy file uploading can be and is not tied to SSL, Firefox, IE, Chrome, etc.
i managed to work around this bug using flex and java web filter
Flex Code :
var urlVars:URLVariables = new URLVariables();
urlVars.jsessionid = sessionID;
var uploadUrl:String = "http://localhost:8080/mywar;jsessionid="+sessionID;
uploadUrl += "?"+getClientCookies(); //put all client cookies on the query string
var urlRequest:URLRequest = new URLRequest(uploadUrl);
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = urlVars;
//will go first time and get the cookies set see flex docs
var testUpload:Boolean = true;
fileRef.upload(urlRequest,"Filedata",testUpload);
JAVA CODE :
package com.mywar.fileupload;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* #author orasio - spieler
* This filter comes to solve the Firefox ,Chrome and SAFARI file upload issue
* The problem was that the file uploaded by the flex
* FileReference came with a different session and no cookies
* To solve this problem do the following :
*
*
* don't forget to add this filter to the web.xml file
*/
public class FileUploadFilter implements Filter {
private static final String CONTENT_LENGTH = "content-length";
private static final String UPLOAD_SITE_PATH = "/";
private static final String JSESSIONID = "JSESSIONID";
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain filterChain)
throws IOException, ServletException {
if ((request instanceof HttpServletRequest)
&& (response instanceof HttpServletResponse)) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
//httpRequest.getHeader("user-agent"); //Shockwave Flash
String contentLength = httpRequest.getHeader(CONTENT_LENGTH);
boolean isFlexTest = (contentLength!=null
&& Integer.parseInt(contentLength)==0);
if(isFlexTest){
HttpServletResponse httpResponse =
(HttpServletResponse) response;
setAllClientCookie((HttpServletResponse)response, httpRequest);
PrintWriter out = httpResponse.getWriter();
out.println("OK");
out.close();
return;
}
}
filterChain.doFilter(request, response);
}
/*
* write all cookies back to the flex test response
*/
#SuppressWarnings("unchecked")
private void setAllClientCookie(HttpServletResponse httpResponse,
HttpServletRequest httpRequest) {
Enumeration<String> parameterNames =
(Enumeration<String>)httpRequest.getParameterNames();
while (parameterNames.hasMoreElements()) {
String cookieName = (String) parameterNames.nextElement();
//since we get IllegalArgumentException: Cookie name "JSESSIONID" is a reserved token
if(!cookieName.contains(JSESSIONID)) {
Cookie cookie =
new Cookie(cookieName, httpRequest.getParameter(cookieName));
cookie.setPath(UPLOAD_SITE_PATH);
httpResponse.addCookie(cookie);
}
}
}
#Override
public void destroy() {
}
}
I faced the same issue.. File upload was working on all browsers except firefox. In firefox, error#2038 was being thrown while uploading file. The application used SSL..
In my case, even the upload request wasn't being generated from firefox which I could confirm by seeing in firebug's Net panel, the upload URL was not being hit. That means, may be flash runtime in firefox was blocking the upload request.
However, when I ran application in IE, installed the self signed certificate of the application in IE, file upload ambigously and ofcourse amazingly, started working in firefox..
So first please check whether request is even being reached to the server or getting blocked at the client.
Thanks
Looks like this is quite old, but I recently ran into this problem, too. My fix (which is far from optimal) under a Flex + authenticated rails setup was to turn off the session based authentication on the upload script.
Since I really did want at least basic authentication, I stored the username and password that the user logged in with, and wrote the code to send/validate that manually on the rails side. I could never get the "jsessionid" hack to work, as flash doesn't have access to the browser sessions.
I hope this helps someone save a bit of time.
This is an actual flash player bug. Maybe this link will give you some ideas.
What do you have on the server side? Maybe you could add the sessionid as a parameter in your request.
Some times even if we send the cookies through the URL it will not work. This is because the Flex is blocking the file upload request.
To unblock it you have to install the SSL certificate, and then try it.
If any one has any other answer please let me know.
Since I was building a Flash App for Facebook, I had no access to jsessionid.
I solved this problem by uploading to a HTTPS address instead of HTTP.
One thing that caused me trouble is that in OSX Firefox and Safari (not Chrome), the (FileReferenceInstance).type is null, and the (FileReferenceInstance).name comes with the full extension (myimage.jpg).