Iam trying since 1 hour to get the absolute path of a file ony server side:
String path = request.getRequestURL();
JasperCompileManager.compileReportToFile(path+"/test.jrxml",path+"/test.jasper");
this didnt work my expection is :
not found : http\12.0.0.13:8080]\test\test.jrxml wrong syntax in dataname...etc
Try this one in your RemoteServiceServlet class to get the absolute path of any resources placed under war directory that will be actually the path of server directory when deployed on server.
String pngFullPath = this.getThreadLocalRequest().getSession().getServletContext()
.getRealPath("images/1.png");
System.out.println(pngFullPath);
String icoFullPath = this.getThreadLocalRequest().getSession().getServletContext()
.getRealPath("favicon.ico");
System.out.println(icoFullPath);
output:
D:\Workspace\GWTProject\war\images\1.png
D:\Workspace\GWTProject\war\favicon.ico
Now change it as per the placement of test.jrxml file in your project.
here is the project structure:
This is the method I use:
public static String getServerBase(HttpServletRequest req)
{
String scheme = req.getScheme(); // http
String serverName = req.getServerName(); // sub.domain.ac.uk
int serverPort = req.getServerPort(); // 80
String contextPath = req.getContextPath(); // /MyApp
return scheme + "://" + serverName + ":" + serverPort + contextPath;
}
Then simply append your file name.
Related
My wish is very simple and basic. However, I can't find any working/clear answer for it :D
I want to know how to delete a file inside a folder in Google Cloud storage.
If let's say I have a bucket name of xxxx.appspot.com and I have a folder inside called images and I have an image inside this folder (E.g. 123.jpg) which I want to delete.
This is the code I wrote, however it didn't delete it:
String bucketName = "xxxx.appspot.com";
GcsService gcsService = GcsServiceFactory.createGcsService();
gcsService.delete(new GcsFilename(bucketName,"images/123.jpg"));
Did I miss anything?
Thanks in Advance!
You can find some code samples in the documentation. In short, what you want to achieve can be done in Java using a couple of lines of code, given that you have the right permissions:
BlobId b = BlobId.of(bucketName, blobName);
boolean deleted = storage.delete(b);
The correct answer as of 2022 is the following:
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class DeleteObject {
public static void deleteObject(String projectId, String bucketName, String objectName) {
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
// The ID of your GCS object
// String objectName = "your-object-name";
Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
storage.delete(bucketName, objectName);
System.out.println("Object " + objectName + " was deleted from " + bucketName);
}
}
Example taken from this page
I am trying to subclass Probe to clone custom repositories from the net before starting the build.
GitProbe:
import qbs
import qbs.File
import qbs.Process
Probe {
property string gitUrl
property string wd
property string name
property string dir: wd + "/" + name
configure: {
try {
if(File.directoryEntries(dir, File.AllEntries).length > 0){
File.remove(dir)
}
var gitProcess = Process()
gitProcess.setWorkingDirectory(wd)
gitProcess.exec("git", ["clone", gitUrl], true)
found = true
} catch(err) {
console.warn("GitProbe : could not clone repository " + gitUrl)
console.error("GitProbe : " + err)
found = false
}
}
}
I did put the GitProbe.qbs in dir/imports/ , and in my project I did qbsSearchPath: "path-to-dir", but qbs tell me when parsing the file Unexpected item type 'GitProbe'.
This is a known limitation: The search path needs to be set already when the current file is parsed. So the workaround is to reference your file from a Project item in another file and set the search path there. You might want to vote on https://bugreports.qt.io/browse/QBS-667.
In my application, I have files in FTP server one directory and I move that file source to target path. In this process, when I move selected source file that source file will not show in the source path, it will show only in target path.
I tried this below code, but I am getting error:
string sourceurl = "ftp://ftp.com/Mainfoder/Folder1/subfolder/subsubfolder/"
string Targetpat =
"ftp://ftp.com/Mainfoder/DownloadedFiles/"+subfolder+"/"+todaydatefolder+"/"+susubfolder;
Uri serverFile = new Uri(sourceurl + filename);
request = (FtpWebRequest)FtpWebRequest.Create(serverFile);
request.Method = WebRequestMethods.Ftp.Rename;
request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
request.RenameTo = Targetpat+"/"+newfilename;//folders without filename
response = (FtpWebResponse)request.GetResponse();
Stream ftpStream = response.GetResponseStream();
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The remote server returned an error: (553) File name now allowed.
response = (FtpWebResponse)request.GetResponse(); //This line throwing the above exception
request.RenameTo = newfilename: when I set only newfilename, it renames that source same file name only.
How can I move this file to another directory within in same FTP server?
Please can anyone tell me. Thank you
As I wrote you already before:
request.RenameTo takes a path only.
So this is wrong:
string Targetpat =
"ftp://ftp.com/Mainfoder/DownloadedFiles/"+subfolder+"/"+todaydatefolder+"/"+susubfolder;
request.RenameTo = Targetpat+"/"+newfilename;
It should be:
string Targetpat =
"/Mainfoder/DownloadedFiles/"+subfolder+"/"+todaydatefolder+"/"+susubfolder;
request.RenameTo = Targetpat+"/"+newfilename;
I have built a Server that you can upload files to and download, using Eclipse, servlet and jsp, it's all very new to me. (more info).
Currently the upload system works with the file's name. I want to programmatically assign each file a random key. And with that key the user can download the file. That means saving the data in a config file or something like : test.txt(file) fdjrke432(filekey). And when the user inputs the filekey the servlet will pass the file for download.
I have tried using a random string generator and renameTo(), for this. But it doesn't work the first time, only when I upload the same file again does it work. And this system is flawed, the user will receive the file "fdjrke432" instead of test.txt, their content is the same but you can see the problem.
Any thoughts, suggestions or solutions for my problem?
Well Sebek, I'm glad you asked!! This is quite an interesting one, there is no MAGIC way to do this. The answer is indeed to rename the file you uploaded. But I suggest adding the random string before the name of the file; like : fdjrke432test.txt.
Try this:
filekey= RenameRandom();
File renamedUploadFile = new File(uploadFolder + File.separator+ filekey+ fileName);
item.write(renamedUploadFile);
//remember to give the user the filekey
with
public String RenameRandom()
{
final int LENGTH = 8;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random()*26)+97));
}
System.out.println(sb.toString());
return sb.toString();
}
To delete or download the file from the server you will need to locate it, the user will input the key, you just need to search the upload folder for a file that begins with that key:
filekey= request.getParameter("filekey");
File f = new File(getServletContext().getRealPath("") + File.separator+"data");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filekey);
}
});
String newfilename = matchingFiles[0].getName();
// now delete or download newfilename
Is there an easy way to tell Selenium IDE that any action that results in a http 500 response means the test failed?
I have tests that are 75 page requests long. Sometimes, I get a crash and burn somewhere in the middle, but the tests come back green.
Taking a look at selenium-api.js, I saw that there is a parameter ignoreResponseCode in the signature of the doOpen method in selenium-api.js :
Selenium.prototype.doOpen = function(url, ignoreResponseCode) {
This parameter is used by the browserbot object :
if (!((self.xhrResponseCode >= 200 && self.xhrResponseCode <= 399) || self.xhrResponseCode == 0)) {
// TODO: for IE status like: 12002, 12007, ... provide corresponding statusText messages also.
LOG.error("XHR failed with message " + self.xhrStatusText);
e = "XHR ERROR: URL = " + self.xhrOpenLocation + " Response_Code = " + self.xhrResponseCode + " Error_Message = " + self.xhrStatusText;
self.abortXhr = false;
self.isXhrSent = false;
self.isXhrDone = false;
self.xhrResponseCode = null;
self.xhrStatusText = null;
throw new SeleniumError(e);
}
I've tried calling the open function from selenium IDE with value = false and this results in an error (test failed).
My PHP test page was :
<?php
header('HTTP/1.1 500 Simulated 500 error');
?>
And this results in :
For me, this solves the problem of checking HTTP response status.
Make a JavaScript file called "user-extensions.js" and add it to the Selenium-IDE under Options > Options. If you are running Selenium RC, pass it into the parameter when starting up your server in the jar command. There should be a user extensions javascript file attribute.
Then close and restart Selenium-IDE. The User-Extensions file is cached when the IDE starts up.
Add this code to your Selenium user-extensions.js file to make a custom command called "AssertLocationPart". As you know "assertLocation" and "storeLocation" are standard commands. I tried to reduce the extra line of code to storeLocation just by getting the href in the custom function. I wasn't able to get the doAssertValue command to work. I'll have to post my own question for that. That's why it's commented out. For now, just use "this.doStore" instead. And add an extra line to your script after your custom AssertLocationPart command. Since we're not actually doing an assertion in the custom function/command, we should call it "storeLocationPart" (function would be named "doStoreLocationPart"), not "assertLocationPart" (function would be named "doAssertLocationPart"), and just pass in the first parameter. But if you can get the doAssert* to work, please let me know. I'll mess with it another day since I need to do this same thing for work.
Selenium.prototype.doAssertLocationPart = function(partName,assertTo) {
var uri = selenium.browserbot.getCurrentWindow().document.location.href;
//alert("URI = " + uri);
var partValue = parseUri(uri,partName);
//alert("Part '" + partName + "' = " + partValue);
//this.doAssertValue(partValue,assertTo);
this.doStore(partValue,"var_"+partName);
};
// Slightly modified function based on author's original:
// http://badassery.blogspot.com/2007/02/parseuri-split-urls-in-javascript.html
//
// parseUri JS v0.1, by Steven Levithan (http://badassery.blogspot.com)
// Splits any well-formed URI into the following parts (all are optional):
//
// - source (since the exec() method returns backreference 0 [i.e., the entire match] as key 0, we might as well use it)
// - protocol (scheme)
// - authority (includes both the domain and port)
// - domain (part of the authority; can be an IP address)
// - port (part of the authority)
// - path (includes both the directory path and filename)
// - directoryPath (part of the path; supports directories with periods, and without a trailing backslash)
// - fileName (part of the path)
// - query (does not include the leading question mark)
// - anchor (fragment)
//
function parseUri(sourceUri,partName){
var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
var uri = {};
for(var i = 0; i < 10; i++){
uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
if (uriPartNames[i] == partName) {
return uri[uriPartNames[i]]; // line added by MacGyver
}
}
// Always end directoryPath with a trailing backslash if a path was present in the source URI
// Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
if(uri.directoryPath.length > 0){
uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
if (partName == "directoryPath") {
return uri.directoryPath; // line added by MacGyver
}
}
return uri;
}
Then add this to your web.config file and make sure customErrors is turned off. Since you have a 500 error, it will redirect the user to the default page. Feel free to add a custom page for a 500 HTTP status code if you want to be specific in your Selenium scripts.
<customErrors mode="On" defaultRedirect="/ErrorHandler.aspx">
<error statusCode="401" redirect="/AccessDenied.aspx" />
<error statusCode="403" redirect="/AccessDenied.aspx" />
<error statusCode="404" redirect="/PageNotFound.aspx" />
</customErrors>
This is what your commands will look like in the IDE:
Make sure you're on this page (or something similar) before running the script:
https://localhost/ErrorHandler.aspx?aspxerrorpath=/path/pathyouweretryingtoviewinwebapp.aspx
Log shows that it passed!
[info] Executing: |storeLocation | var_URI | |
[info] Executing: |echo | ${var_URI} | |
[info] echo: https://localhost/ErrorHandler.aspx?aspxerrorpath=//path/pathyouweretryingtoviewinwebapp.aspx
[info] Executing: |assertLocationPart | fileName | ErrorHandler.aspx |
[info] Executing: |assertExpression | ${var_fileName} | ErrorHandler.aspx |
Using the error handler from my previous answer:
Command: assertLocation
Target: regexp:^(https://localhost/ErrorHandler.aspx).*$
Or (per your comment) it's inverse if you don't have error handling turned on, use AssertNotLocation. This may require more work on the person writing the scripts. You'd have to keep track of all pages.
More on pattern matching:
http://seleniumhq.org/docs/02_selenium_ide.html#matching-text-patterns
http://www.codediesel.com/testing/selenium-ide-pattern-matching/