FileConnection fc = (FileConnection)Connector.open("file:///C:/products.dat",Connector.READ_WRITE);
if(!fc.exists())
{
fc.create();
OutputStream os=fc.openOutputStream();
byte[] b=response.toString().getBytes();
os.write(b);
os.flush();
fc.close();
}
It seems that path that you are providing is not a valid root.
To check For a list of all the valid root values in a device, call the listRoots() method of FileSystemRegistry.
other reason may be for some reason FileSystemRegistry can not access that path(disk error or read protected).
Related
How/where can I compute md5 digest for a file I need to transfer to a samba location in spring-integration in order to validate it against the digest I receive at the beginning of the flow. I get the file from a rest service and I have to make sure file is safely landing to samba location. The middle flow looks like this: (the digest to be compared against is stored somewhere in the messages)
GenericHandler smbUploader;
HttpRequestExecutingMessageHandler httpDownloader;
from(inbound()) //here I receive a notification with url where to download file + a checksum to be validated against
...
.handle(httpDownloader) //here I get file effectively
.handle(smbUploader) //here I upload the file to samba
...
and httpDownloader is defined like this:
public HttpRequestExecutingMessageHandler httpDownloader(){
HttpRequestExecutingMessageHandler h = new HttpRequestExecutingMessageHandler ("payload.url");
h.setExpectedResponseType(String.class);
h.setHttpMethod(GET);
return h;
}
and smbUploader is defined like this:
public GenericHandler smbUploader (MessageHandler smbMessageHandler){
return new GenericHandler<Message>(){
#Override
public Message handle(Message m, MessageHeaders h){
smbMessageHandler.handleMessage(m);
return m;
}
}
and smbMessageHandler is defined like this:
public MessageHandler smbMessageHandler (SmbRemoteFileTemplate template, FileNameGenerator g){
SmbMessageHandler h = new smbMessageHandler (template, REPLACE);
h.setAutoCreateDirectory(true);
h.setRemoteDirectoryExpression(getExpression("headers['msg'].smbFolder"));
h.setFileNameGenerator(g);
return h;
}
the inbound (starting the flow) is defined like this:
public HttpRequestHandlerEndpointSpec inbound(){
return Http.inboundChannelAdapter ("/notification")
.requestMapping(m->m.methods(POST))
.requestPayloadType(String.class)
.validator(notificationValidator);
}
First of all you should store a digest in the message headers in the beginning of the flow.
Then you need to write a service method to calculate a checksum of the file you got downloaded. And insert a new handle() in between:
.handle(httpDownloader) //here I get file effectively
.handle(smbUploader) //here I upload the file to samba
to call your service method. The input for that method must be a whole Message, so you got access to the downloaded file in the payload and digest in the headers. The result of this method could be just your file to proceed into an SMB handler for uploading.
How to calculate a checksum you can find in this SO thread: Getting a File's MD5 Checksum in Java
I need to access a memory mapped file from one of my routes in my Web API. Using the normal IIS worker settings I have no luck and my service always returns "File not found". I tried to add the prefix "Global/" but still no luck.
After reading many hours on the web I learned that I need to change the Identity of the IIS worker. So, just for testing purposes I changed the worker identity to the Administrator account. I uploaded a picture here:
http://imgur.com/MrA3byz
But still no luck. Does anyone here know how to configure IIS correctly?
Here is how I access the Memory Mapped File using c#:
string Message = "";
try
{
string MMF_In_Name = "Global\\MMF_Name";
MemoryMappedFile MMF_In = MemoryMappedFile.OpenExisting(MMF_In_Name);
Messages.Add("Connected to MMF");
}
catch (Exception ex)
{
Messages.Add(ex.Message);
}
I have double checked the name of the memory mapped file and it's correct. A command line tool run as Administrator works as expected.
I'm using IIS 8.5 on Windows Server 2012.
This works on Windows Server 2012 and IIS 8.5.
It's important to understand that the IIS worker runs in a different Terminal Server Session than normal applications. Much like a Windows Service.
So when the application exposing a Memory Mapped File it needs create it via the "Global\" prefix added to the name. But it also needs add a security descriptor or identity. In c# it would look like this:
string MMF_Name = #"Global\MyMemoryMappedFileName";
var security = new MemoryMappedFileSecurity();
security.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null)
, MemoryMappedFileRights.FullControl
, AccessControlType.Allow)
);
var mmf = MemoryMappedFile.CreateOrOpen(MMF_Name
, 1024 * 1024
, MemoryMappedFileAccess.ReadWrite
, MemoryMappedFileOptions.None
, security
, System.IO.HandleInheritability.Inheritable);
In C++ it would look like this:
TCHAR szName[] = TEXT("Global\MyMemoryMappedFileName");
HANDLE hMapFile;
LPCTSTR pBuf;
SECURITY_DESCRIPTOR sd;
if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION))
printf("InitializeSecurityDescriptor failed %d\n", GetLastError());
if (!SetSecurityDescriptorDacl(&sd, true, 0, false))
printf("SetSecurityDescriptorDacl failed %d\n", GetLastError());
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = &sd;
sa.bInheritHandle = false;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
&sa, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
BUF_SIZE, // maximum object size (low-order DWORD)
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"),
GetLastError());
return 1;
}
An application creating such objects needs to start with Admin rights.
Now when a client like the IIS worker tries to access the file it needs to make sure to use the correct name, aka use the "Global\" prefix. In C# it would look like:
string MMF_Name = #"Global\MyMemoryMappedFileName";
var MMF = MemoryMappedFile.OpenExisting(MMF_Name
, MemoryMappedFileRights.ReadWrite
, HandleInheritability.Inheritable);
In C++:
TCHAR szName[] = TEXT("Global\\MyMemoryMappedFileName");
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
TRUE, // !!!!! do inherit the name
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not open file mapping object (%d).\n"),
GetLastError());
return 1;
}
When all this is done. The IIS worker should be able to access the application via the memory mapped file. No need to change the identity of the worker. In fact, I run it in default settings.
I want to implement a behavior similar to Whatsapp, where when the user can upload an image. I tried opening the images in my app, but if the image is too large, I will have an out of memory error.
To solve this, I'm opening forwarding the images to be open in the phone's native image viewer using the platformRequest() method.
However, I want to know how is it Whatsapp modifies the phone's native image viewer to add a "Select" button, with which the user selects the image he wants to upload. How is that information sent back to the J2ME application and how is the image resized?
Edit:
I tried this in two different ways, both of which gave me the OOME.
At first, I tried the more direct method:
FileConnection fc = (FileConnection) Connector.open("file://localhost/" + currDirName + fileName);
if (!fc.exists()) {
throw new IOException("File does not exists");
}
InputStream fis = fc.openInputStream();
Image im = Image.createImage(fis);
fis.close();
When that didn't work, I tried a more "manual" approach, but that gave me an error as well.
FileConnection fc = (FileConnection) Connector.open("file://localhost/" + currDirName + fileName);
if (!fc.exists()) {
throw new IOException("File does not exists");
}
InputStream fis = fc.openInputStream();
ByteArrayOutputStream file = new ByteArrayOutputStream();
int c;
byte[] data = new byte[1024];
while ((c = fis.read(data)) != -1) {
file.write(data, 0, c);
}
byte[] fileData = null;
fileData = file.toByteArray();
fis.close();
fc.close();
file.close();
Image im = Image.createImage(fileData, 0, fileData.length);
When I call the createImage method, the out of memory error occurs in both cases.
This varies with the devices. An E72 gives me the error with 3MB images, while a newer device will give me the error with images larger than 10MBs.
MIDP 2 (JSR 118) does not have API for that, you need to find another way to handle big images.
As for WhatsApp, it looks like they do not rely on MIDP in supporting this functionality. If you check the Wikipedia page you'll note that they don't claim general Java ME as supported platform, but instead, list narrower platforms like Symbian, S40, Blackberry etc.
This most likely means that they implement "problematic features" like one you're asking about using platform-specific API of particular target devices, having essentially separate projects / releases for every platform listed.
If this feature is really necessary in your application, you likely will have to do something like this.
In this case, consider also encapsulating problematic features in a way to make it easier to switch just part of your source code when building it for different platforms. For example, Class.forName(String) can be used to load platform specific implementation depending on target platform.
//...
Image getImage(String resourceName) {
// ImageUtil is an interface with method getImage
ImageUtil imageUtil = (ImageUtil) Class.forName(
// get platform-specific implementation, eg
// "mypackage.platformspecific.s40.S40ImageUtil"
// "mypackage.platformspecific.bb.BBImageUtil"
// "mypackage.platformspecific.symbian.SymbialImageUtil"
"mypackage.platformspecific.s40.S40ImageUtil");
return imageUtil.getImage(resourceName);
}
//...
I need to know a way to connect to a FTP site and i am unable to find an example to do the program using C#.
I need to write the code where i could connect, and download files from the FTP server without using third party component.
How can i do this ? Help.
There is FtpWebRequest class in .Net 4
http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx
There are examples at the end. Here is a sample taken from msdn:
public static bool DisplayFileFromServer(Uri serverUri)
{
// The serverUri parameter should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
WebClient request = new WebClient();
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
try
{
byte [] newFileData = request.DownloadData (serverUri.ToString());
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
Console.WriteLine(fileString);
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
return true;
}
This isn't specifically a question as such.
You need to use the socket classes within the .NET framework:
MSDN - System.Net.Sockets
A good example I've previously used is:
www.dreamincode.net - Create an ftp class library
I am developing an mobile application using j2me.In that i am using kxml parser.In my application i have to call an url to get the data.When i am calling that url sometimes it showing:
java.lang.IllegalStateException: update of non-existent node Exception.
My sample code is:
InputStreamReader isr=null;
InputStream rssStream=null;
InputStream is = null;
HttpConnection conn=null;
try
{
conn = (HttpConnection)Connector.open(rssUrl);
rssStream = conn.openInputStream();---------->I think exception is shown here.
isr = new InputStreamReader( rssStream );
parser.setInput(isr);
parser.nextTag();
Better you replace the code
rssStream = conn.openInputStream();---------->I think exception is shown here.
isr = new InputStreamReader( rssStream );
with the following code
isr = conn.openInputStream();
Then try it.
The XML content returned by rssUrl is probably mal-formed. Download the content to a local file and check it.
If it is mal-formed, can you change the url content?