I'm using the code below to retrieve an attachment from a webserver. The client in this case is a web browser. So currently, the user makes a request to a webserver for the attachment. The webserver makes an MTOM request to another server for the attachment. That webserver then waits for the attachment to download before it begins writing that attachment out to the response. The user is waiting twice as long to get the file. How can I tap into the Axis2 code to get access to the temp file so that I can stream it to the user as it is being created? I know this doesn't sound like the best way to do this, but this is the requirement. I'm working with large files up to 2GB, so waiting twice as long to recieve the file isn't working out.
Options options = new Options();
options.setTo(new EndpointReference(this.endpointUrl));
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
options.setProperty(Constants.Configuration.CACHE_ATTACHMENTS, Constants.VALUE_TRUE);
options.setProperty(Constants.Configuration.ATTACHMENT_TEMP_DIR, this.tempDirectory);
options.setProperty(Constants.Configuration.FILE_SIZE_THRESHOLD, String.valueOf(this.tempFileSizeThreshold));
options.setTimeOutInMilliSeconds(this.serviceRequestTimeOut);
sender = new ServiceClient();
sender.setOptions(options);
OMElement result = sender.sendReceive(this.getAttachmentPayload(productId, attachmentId));
OMElement attachmentElement = result.getFirstElement();
Iterator<OMElement> elementIterator = attachmentElement.getChildElements();
String fileName = "";
DataHandler dataHandler = null;
while (elementIterator.hasNext()) {
OMElement element = elementIterator.next();
if (element.getQName().getLocalPart().equals("name")) {
fileName = element.getText();
} else if (element.getQName().getLocalPart().equals("attachment")) {
dataHandler = (DataHandler) ((OMText) element.getFirstOMChild()).getDataHandler();
}
}
org.w3.www._2005._05.xmlmime.Base64Binary b64data = ---YOUR_SOURCE_ATTACHMENT---;
org.apache.axiom.attachments.CachedFileDataSource ds = (CachedFileDataSource) b64data.getBase64Binary().getDataSource();
String absPath = ds.getFile().getAbsolutePath();
Related
I have a Blazor Application which had files uploaded to a upload folder on the web server. I am in the process of trying to figure out the code to download an uploaded file in the browser for retrieval and viewing. Right now the code is as below (the download part from code examples on the internet)
public void FileDetailsToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
string path = null;
string uploads = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot\\uploads");
path = uploads + "\\" + SelectedFileName;
if (args.Item.Text == "Delete")
{
//Code for Deleting goes here
//UploadRef.Remove();
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
FileDetailsService.FileDetailsDelete(SelectedFileId); //NavigationManager.NavigateTo($"/ServiceRequestNotes/servicerequestnoteadd");
NavigationManager.NavigateTo($"/ServiceRequests/serviceRequestsaddedit2/{Id}", forceLoad: true);
}
else
{
// its a download
IFileProvider provider = new PhysicalFileProvider(uploads);
IFileInfo fileinfo = provider.GetFileInfo(path + SelectedFileName);
var readStream = fileinfo.CreateReadStream();
var mimeType = "application/pdf";
return File(readStream, mimeType, SelectedFileName);
}
}
On the last statement I am a getting the following error message
non-invocable member 'File' cannot be used like a method error message
What am I missing or do I need to change or add to have the output from the readstream render to the browser?
The blazor application is a blazor server app not WASM. It does not make use of API controllers.
Any advice?
This is a void method. You can't return anything at all. Also, if you're trying to instantiate a File object, you'd have to use the new keyword.
I have a JWS application that caches several different resource types. However, I do not want to cache .svg images. It seems that the framework does not honor the server side cache control HTTP headers that I have set.
I was wondering if there is some other way that I could load .svg images without caching. I am open to putting a solution in my loadSVGDocument() method, but my code is currently built around Apache Batik for loading .svg files. Is there a solution to pass an InputStream with a noCache flag within the Batik library similar to what DocumentBuilderFactory provides below?
URL url = new URL(fileLocation);
URLConnection connection = url.openConnection();
// Prevent JavaWebStart from returning cached copy.
connection.setUseCaches(false);
// Now fetch the content, e.g.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(connection.getInputStream());
Here is my current loadSVGDocument() method that uses several Apache Batik fields:
public void loadSVGDocument(final String url)
{
System.out.println("THE SVG URL: " + url);
String oldURI = null;
if (svgDocument != null)
{
oldURI = svgDocument.getURL();
}
final ParsedURL newURI = new ParsedURL(oldURI, url);
String theUrl = newURI.toString();
fragmentIdentifier = newURI.getRef();
loader = new DocumentLoader(userAgent);
nextDocumentLoader = new SVGDocumentLoader(theUrl, loader);
nextDocumentLoader.setPriority(Thread.NORM_PRIORITY);
Iterator it = svgDocumentLoaderListeners.iterator();
while (it.hasNext())
{
nextDocumentLoader
.addSVGDocumentLoaderListener((SVGDocumentLoaderListener) it.next());
}
documentLoader = nextDocumentLoader;
nextDocumentLoader = null;
documentLoader.run();
}
For anyone interested, I found that I can call Batik's
DocumentLoader.loadDocument(URL url, InputStream is)
with the setUseCaches flag as false. Not only does this load the image, but it also removes it from the cache accordingly. Though not the best solution in the sense that it would be nice for JWS to honor my HTTP headers, this work-around is good enough.
I'm trying to use the oneDrive REST API to get files in a specific folder.
I have the path to the folder (For example "myApp/filesToDownload/", but don't have the folder's oneDrive ID. Is there a way to get the folder ID or the files in the folder with the REST API?
The only way I see to get it is by using https://apis.live.net/v5.0/me/skydrive/files?access_token=ACCESS_TOKEN
to get the list of folders in the root, and then splitting the path string on "/" and looping on it, each time doing a GET https://apis.live.net/v5.0/CURRENT_FOLDER/files?access_token=ACCESS_TOKEN request for each hierarchy.. I would prefer to avoid doing all those requests because the path may be quite long..
Is there a better/simpler way of getting the files of a specific folder?
Thanks
As Joel has pointed out, Onedrive API supports path based addressing also (in addition to ID based addressing). So you don't need the folder ID. You can use the Onedrive API (api.onedrive.com) for getting the files/folders of a specific folder as follows:
String path = "path/to/your/folder"; // no '/' in the end
HttpClient httpClient = new DefaultHttpClient();
// Forming the request
HttpGet httpGet = new HttpGet("https://api.onedrive.com/v1.0/drive/root:/" + path + ":/?expand=children");
httpGet.addHeader("Authorization", "Bearer " + ACCESS_TOKEN);
// Executing the request
HttpResponse response = httpClient.execute(httpGet);
// Handling the response
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONObject finalResult = new JSONObject(tokener);
JSONArray fileList = null;
try{
fileList = finalResult.getJSONArray("children");
for (int i = 0; i < fileList.length(); i++) {
JSONObject element = (JSONObject) fileList.get(i);
// do something with element
// Each element is a file/folder in the form of JSONObject
}
} catch (JSONException e){
// do something with the exception
}
For more details see here.
I am working on pdf generation, it is successfully implemented using itextsharp.dll. It’s working fine on local environment after publish also. We have our own server at other site
But same code doesn't work on the server,pdf is not generated instead it gives an error: 'The document has no pages.'
Initially I thought it is due to no data in document but it works locally with or without data in the document.
I had code implemented as follows to make a web request Is any problem in that ??
try
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strPdfData + "?objpatId=" + patID);
var response = myHttpWebRequest.GetResponse();
myHttpWebRequest.Timeout = 900000;
var stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
content = sr.ReadToEnd();
}
create a method in the controller:
[HttpGet]
public JsonResult GetFile()
{
var json = new WebClient().DownloadFile(string address, string fileName);
//This code is just to convert the file to json you can keep it in file format and send to the view
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var oc = Newtonsoft.Json.JsonConvert.DeserializeObject<countdata[]>(Convert.ToString(result.countdata));
return Json(oc, JsonRequestBehavior.AllowGet);
}
In the view just call this function:
#Url.Action('genPDF','GetFile');
I have a simle program shown below which is resonsible to upload a file to a Remote Location
public static void main(String[] args) {
String server = "www.myserver.com";
int port = 21;
String user = "user";
String pass = "pass";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
File firstLocalFile = new File("D:/Test/Projects.zip");
String firstRemoteFile = "Projects.zip";
InputStream inputStream = new FileInputStream(firstLocalFile);
System.out.println("Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
}
My question is , is it possible to test this program anyway , as i dont have a Remote Server currently .
Means is it possible to get remote server to upload files for temporary purpose ( Sorry but only open source please )
Is anybody aware of such websites ??
Screen shot