I'm trying to download a file using HTTP, and here is the code.
With this, I have a directory made with a correct name, and a file within the directory made with a correct name, but there is NOTHING WRITTEN in the file.
PostMethod post = new PostMethod(serverUrl);
post.setRequestEntity(entity);
httpclient.executeMethod(post);
File contentDirectory = new File(fileFullPath);
if(contentDirectory.exists() == false){
contentDirectory.mkdir();
}
File localFile = new File(fileFullPath + File.separator + filename);
int readBuf = 0;
byte[] buf = new byte[Utils.getBufferSize()]; (BufferSize Checked)
InputStream is = null;
is = post.getResponseBodyAsStream();
FileOutputStream fos = new FileOutputStream(localFile);
while((readBuf = is.read(buf))!= -1){
fos.write(buf, 0, readBuf);
logger.info("readBuf : "+readBuf);
}
is.close();
fos.close();enter code here
if(localFile.exists()) Transfer_Success = true;
Being a noob I am, turns out all this time I was sending post method to a wrong servlet. A mistake only novices make.
So I have the bytes transferred correctly, but this time the image files can't be open due to wrong encoding type or something. I'm on to resolving this.
Related
As the title suggests, WLP won't run the process- it won't return anything to the process input stream nor to error stream.
If anyone knows about a configuration that needs to take place I would love to know..
(note the process Can run by running the command manually - in addition, the whole thing runs smooth on tomcat8 so..)
EDIT 1:
The problem was not the command execution under WLP as you guys stated, so I accepted the answer.
The problem is different : I sent a media file to a multipart servlet and stored it in a file on disk using the following code:
InputStream is = request.getInputStream();
String currentTime = new Long(System.currentTimeMillis()).toString();
String fileName = PATH + currentTime + "." + fileType;
File file = new File(fileName);
// write the image to a temporary location
FileOutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[BUFFER_SIZE];
while(true) {
int numRead = is.read(buffer);
if(numRead == -1) {
break;
}
os.write(buffer, 0, numRead);
os.flush();
}
is.close();
os.close();
and the file gets saved along with the following prefix:
While this does not happen on tomcat8 (using the same client)..
something is not trivial in the received input stream. (Note its a multipart servlet that set up via #MultipartConfig only)
Hope this post will help others..
guys,thanks for your help!
This will work in Liberty. I was able to test out the following code in a servlet and it printed the path of my current directory just fine:
String line;
Process p = Runtime.getRuntime().exec("cmd /c cd");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
Start with a simple command like this, and when you move up to more complex commands or scripts, make sure you are not burying exceptions that may come back. Always at least print the stack trace!
I'm trying to upload a large file to a document library, but it fails after just a few seconds. The upload single document fails silently, upload multiple just shows a failed message. I've turned up the file size limit on the web application to 500MB, and the IIS request length to the same (from this blog), and increased the IIS timeout for good measure. Are there any other size caps that I've missed?
Update I've tried a few files of various sizes, anything 50MB or over fails, so I assume something somewhere is still set to the webapp default.
Update 2 Just tried uploading using the following powershell:
$web = Get-SPWeb http://{site address}
$folder = $web.GetFolder("Site Documents")
$file = Get-Item "C:\mydoc.txt" // ~ 150MB
$folder.Files.Add("SiteDocuments/mydoc.txt", $file.OpenRead(), $false)
and get this exception:
Exception calling "Add" with "3" argument(s): "<nativehr>0x80070003</nativehr><nativestack></nativestack>There is no file with URL 'http://{site address}/SiteDocuments/mydoc.txt' in this Web."
which strikes me as odd as of course the file wouldn't exist until it's been uploaded? N.B. while the document library has the name Site Documents, it has the URL SiteDocuments. Not sure why...
Are you sure you updated the right webapp? Is the filetype blocked by the server? Is there adequate space in your content database? I would check ULS logs after that and see if there is another error since it seems you hit the 3 spots you would need too update.
for uploading a large file, you can use the PUT method instead of using the other ways to upload a document.
by using a put method you will save the file into content database directly. see the example below
Note: the disadvantage of the code below is you cannot catch the object that is responsible for uploading directly, on other word, you cannot update the additional custom properties of the uploaded document directly.
public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath)
{
//Flag to indicate whether file was uploaded successfuly or not
bool isUploaded = true;
try
{
// Create a PUT Web request to upload the file.
WebRequest request = WebRequest.Create(targetDocumentLibraryPath);
//Set credentials of the current security context
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = “PUT”;
// Create buffer to transfer file
byte[] fileBuffer = new byte[1024];
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
{
//Get the start point
int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
}
// Perform the PUT request
WebResponse response = request.GetResponse();
//Close response
response.Close();
}
catch (Exception ex)
{
//Set the flag to indiacte failure in uploading
isUploaded = false;
}
//Return the final upload status
return isUploaded;
}
and here are an example of calling this method
UploadFileToDocumentLibrary(#”C:\test.txt”, #”http://home-vs/Shared Documents/textfile.pdf”);
I am getting "The given path's format is not supported." when I am just trying to download multimedia image from my SDL Tridion 2011 SP1, below is the path I am getting, no idea how "N:" etc are coming.
D:\delete\Images\N:\dmc.FlipMedia.Clients.TestCMS\2009_WorkInProgress\creatives\05_May\Kids under 16 go free to UK\assets_graphics\jpg\Kids_go_free_385x306.jpg
Below is the code:
public static void GetBinaryFromMultimediaComponent(string tcm, CoreServiceClient client, StreamDownloadServiceClient streamDownloadClient)
{
ComponentData multimediaComponent = client.ReadItem(tcm) as ComponentData;
// Generate you own file name, and file location
string file = "D:\\delete\\Images\\" + multimediaComponent.BinaryContent.Filename;//Here I am getting above path
// Write out the existing file from Tridion
FileStream fs = File.Create(file);//Here getting the exception
byte[] binaryContent = null;
if (multimediaComponent.BinaryContent.FileSize != -1)
{
Stream tempStream = streamDownloadClient.DownloadBinaryContent(tcm);
var memoryStream = new MemoryStream();
tempStream.CopyTo(memoryStream);
binaryContent = memoryStream.ToArray();
}
fs.Write(binaryContent, 0, binaryContent.Length);
fs.Close();
}
Please suggest!!
Edit:
I got filename using Nuno Suggestions, however moving forward to
Stream tempStream = streamDownloadClient.DownloadBinaryContent(tcm);
I am getting below error, any suggestion on this?
The content type multipart/related; type="application/xop+xml";start="";boundary="uuid:5f66d04b-76d3-4d3a-b8e3-b7b91e00ed32+id=2";start-info="text/xml" of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 595 bytes of the response were: ' --uuid:5f66d04b-76d3-4d3a-b8e3-b7b91e00ed32+id=2 Content-ID: Content-Transfer-Encoding: 8bit Content-Type: application/xop+xml;charset=utf-8;type="text/xml" '.
As you probably figured out by now, string file = "D:\\delete\\Images\\" + multimediaComponent.BinaryContent.Filename;will append full file name (including path) and therefore generate a wrong path.
Try using something like string file = "D:\\delete\\Images\\" + Path.GetFilename(multimediaComponent.BinaryContent.Filename);
Do this way:-
Stream tempStream = streamDownloadClient.DownloadBinaryContent(tcmId);
MemoryStream memoryStream = new MemoryStream();
int b;
do
{
b = tempStream.ReadByte();
memoryStream.WriteByte((byte)b);
} while (b != -1);
binaryContent = memoryStream.ToArray();
I am trying to create a upload servlet that handles enctype="multipart/form-data" from a form. The file I am trying to upload is a zip. However, I can upload and read the file on localhost, but when I upload to the server, I get a "File not found" error when I want to upload a file. Is this due to the Struts framework that I am using? Thanks for your help. Here is part of my code, I am using FileUpload from http://commons.apache.org/fileupload/using.html
I have changed to using ZipInputStream, however, how to I reference to the ZipFile zip without using a local disk address (ie: C://zipfile.zip). zip is null because its not instantiated. I will need to unzip and read the zipentry in memory, without writing to the server.
For the upload servlet:
>
private ZipFile zip;
private CSVReader reader;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List <FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
//Iterating through the uploaded zip file and reading the content
FileItem item = (FileItem) iter.next();
ZipInputStream input = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while (( entry= input.getNextEntry()) != null) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.getName().toString().equals("file.csv")){
//unzip(entry)
}
}
}
public static void unzip(ZipEntry entry){
try{
InputStream inputStream = **zip**.getInputStream(entry);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new CSVReader(inputStreamReader);
}
catch(Exception e){
e.printStackTrace();
}
}
<
Here,
zip = new ZipFile(new File(fileName));
You're assuming that the local disk file system at the server machine already contains the file with exactly the same name as it is at the client side. This is a wrong assumption. That it worked at localhost is obviously because both the webbrowser and webserver "by coincidence" runs at physically the same machine with the same disk file system.
Also, you seem to be using Internet Explorer as browser which incorrectly includes the full path in the filename like C:/full/path/to/file.ext. You shouldn't be relying on this browser specific bug. Other browsers like Firefox correctly sends only the file name like file.ext, which in turn would have caused a failure with new File(fileName) (which should have helped you to spot your mistake much sooner).
To fix this "problem", you need to obtain the file contents as InputStream by item.getInputStream():
ZipInputStream input = new ZipInputStream(item.getInputStream());
// ...
Or to write it to disk by item.write(file) and reference it in ZipFile:
File file = File.createTempFile("temp", ".zip");
item.write(file);
ZipFile zipFile = new ZipFile(file);
// ...
Note: don't forget to check the file extension beforehand, else this may choke.
I have a jsp page which holds a form, it is supposed to send off the form data to a remote servlet, which calculates it, and then returns it as XML. It works, but at the moment I'm creating an instance and dispatcher which only works with local servlets whereas I want it to work with a remote servlet.
I was previously told that HTTPClient would do this, but this thing has become such a headache and it seems like a complete overkill for what I want to do. There must be some simple method as opposed to faffing around with all these jar components and dependencies?
Please give sample code if possible, I'm really a complete novice to Java, much more of a PHP guy :P
Figured it out with the help of some online resources. Had to first collect the submitted values (request.getParamater("bla")), build the data string (URLEnconder), start up a URLConnection and tell it to open a connection with the designated URL, startup an OutputStreamWriter and then tell it to add the string of data (URLEncoder), then finally read the data and print it...
Below is the gist of the code:
String postedVariable1 = request.getParameter("postedVariable1");
String postedVariable2 = request.getParameter("postedVariable2");
//Construct data here... build the string like you would with a GET URL
String data = URLEncoder.encode("postedVariable1", "UTF-8") + "=" + URLEncoder.encode(postedVariable1, "UTF-8");
data += "&" + URLEncoder.encode("postedVariable2", "UTF-8") + "=" + URLEncoder.encode(submitMethod, "UTF-8");
try {
URL calculator = new URL("http://remoteserver/Servlet");
URLConnection calcConnection = calculator.openConnection();
calcConnection.setDoOutput(true);
OutputStreamWriter outputLine = new OutputStreamWriter(calcConnection.getOutputStream());
outputLine.write(data);
outputLine.flush();
// Get the response
BufferedReader streamReader = new BufferedReader(new InputStreamReader(calcConnection.getInputStream()));
String line;
//streamReader = holding the data... can put it through a DOM loader?
while ((line = streamReader.readLine()) != null) {
PrintWriter writer = response.getWriter();
writer.print(line);
}
outputLine.close();
streamReader.close();
} catch (MalformedURLException me) {
System.out.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}