fuse - Setting target of Symbolic link - Java - symlink

I want to make symbolic link in FUSE (Fuse-jna, Java binding of fuse). I implemented readdir() and getattr() correctly but I do not correctly know that how to implement the readlink().
Here is my getattr() method
public int getattr(final String path, final StatWrapper stat)
{
...
stat.setMode(NodeType.SYMBOLIC_LINK);
return 0;
}
I want to set target of my symbolic link as /Documents/Untitled Document
I tried below, but it is not working.
public int readlink(final String path, final ByteBuffer buffer, final long size)
{
CharBuffer cbuf = buffer.asCharBuffer();
cbuf.put("/Documents/Untitled Document");
cbuf.flip();
return 0;
}
Please guide me how to correctly set the target of symbolic link

Sorry,
I have fixed my problem as below.
public int readlink(final String path, final ByteBuffer buffer, final long size)
{
String s = "../Documents/Untitled Document";
byte[] b = s.getBytes(Charset.forName("UTF-8"));
buffer.put(b);
return 0;
}
thanks any way

Related

JavaCV: avformat_open_input() hangs (not network, but with custom AVIOContext)

I'm using a custom AVIOContext to bridge FFMpeg with java IO. The function avformat_open_input() never returns. I have searched the web for similar problems, all of which were caused by faulty network or wrong server configurations. However, I'm not using network at all, as you can see in the following little program:
package com.example;
import org.bytedeco.javacpp.*;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import static org.bytedeco.javacpp.avcodec.*;
import static org.bytedeco.javacpp.avformat.*;
import static org.bytedeco.javacpp.avutil.*;
import static org.bytedeco.javacpp.avdevice.*;
import static org.bytedeco.javacpp.avformat.AVFormatContext.*;
public class Test {
public static void main(String[] args) throws Exception {
File dir = new File(System.getProperty("user.home"), "Desktop");
File file = new File(dir, "sample.3gp");
final RandomAccessFile raf = new RandomAccessFile(file, "r");
Loader.load(avcodec.class);
Loader.load(avformat.class);
Loader.load(avutil.class);
Loader.load(avdevice.class);
Loader.load(swscale.class);
Loader.load(swresample.class);
avcodec_register_all();
av_register_all();
avformat_network_init();
avdevice_register_all();
Read_packet_Pointer_BytePointer_int reader = new Read_packet_Pointer_BytePointer_int() {
#Override
public int call(Pointer pointer, BytePointer buf, int bufSize) {
try {
byte[] data = new byte[bufSize]; // this is inefficient, just use as a quick example
int read = raf.read(data);
if (read <= 0) {
System.out.println("EOF found.");
return AVERROR_EOF;
}
System.out.println("Successfully read " + read + " bytes of data.");
buf.position(0);
buf.put(data, 0, read);
return read;
} catch (Exception ex) {
ex.printStackTrace();
return -1;
}
}
};
Seek_Pointer_long_int seeker = new Seek_Pointer_long_int() {
#Override
public long call(Pointer pointer, long offset, int whence) {
try {
raf.seek(offset);
System.out.println("Successfully seeked to position " + offset + ".");
return offset;
} catch (IOException ex) {
return -1;
}
}
};
int inputBufferSize = 32768;
BytePointer inputBuffer = new BytePointer(av_malloc(inputBufferSize));
AVIOContext ioContext = avio_alloc_context(inputBuffer, inputBufferSize, 1, null, reader, null, seeker);
AVInputFormat format = av_find_input_format("3gp");
AVFormatContext formatContext = avformat_alloc_context();
formatContext.iformat(format);
formatContext.flags(formatContext.flags() | AVFMT_FLAG_CUSTOM_IO);
formatContext.pb(ioContext);
// This never returns. And I can never get result.
int result = avformat_open_input(formatContext, "", format, null);
// all clean-up code omitted for simplicity
}
}
And below is my sample console output:
Successfully read 32768 bytes of data.
Successfully read 32768 bytes of data.
Successfully read 32768 bytes of data.
Successfully read 32768 bytes of data.
Successfully read 32768 bytes of data.
Successfully read 7240 bytes of data.
EOF found.
I've checked the sum of bytes, which corresponds to the file size; EOF is also hit, meaning the file is completely read. Actually I am a bit skeptical as why avformat_open_input() would even read the entire file and still without returning? There must be something wrong with what I am doing. Can any expert shed some lights or point me to the right direction? I'm new to javacv and ffmpeg and especially to programming with Buffers and stuff. Any help, suggestion or criticism is welcome. Thanks in advance.
Ok, now I have found the problem. I have misinterpreted the docs and overlooked most of the examples I found. My bad.
According to the documentation on ffmpeg:
AVIOContext* avio_alloc_context (unsigned char* buffer,
int buffer_size,
int write_flag,
void* opaque,
int(*)(void *opaque, uint8_t *buf, int buf_size) read_packet,
int(*)(void *opaque, uint8_t *buf, int buf_size) write_packet,
int64_t(*)(void *opaque, int64_t offset, int whence) seek
)
The third parameter, write_flag is used in the following fashion:
write_flag - Set to 1 if the buffer should be writable, 0 otherwise.
Actually, it means if the AVIOContext is for data output (i.e. writing), write_flag should be set to 1. Otherwise, if the context is for data input (i.e. reading), it should be set to 0.
In the question I posted, I passed 1 as the write_flag and it is causing the problem when reading. Passing 0 instead solves the problem.
Later I re-read all the examples I found, all the avio_alloc_context() calls uses 0, not 1 when reading. So that further indicates why I'm having the problem.
To conclude, I will post the revised code with the problems corrected as a future reference.
package com.example;
import org.bytedeco.javacpp.*;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import static org.bytedeco.javacpp.avformat.*;
import static org.bytedeco.javacpp.avutil.*;
import static org.bytedeco.javacpp.avformat.AVFormatContext.*;
public class Test {
public static void main(String[] args) throws Exception {
File dir = new File(System.getProperty("user.home"), "Desktop");
File file = new File(dir, "sample.3gp");
final RandomAccessFile raf = new RandomAccessFile(file, "r");
Loader.load(avformat.class);
Loader.load(avutil.class);
av_register_all();
avformat_network_init();
Read_packet_Pointer_BytePointer_int reader = new Read_packet_Pointer_BytePointer_int() {
#Override
public int call(Pointer pointer, BytePointer buf, int bufSize) {
try {
byte[] data = new byte[bufSize]; // this is inefficient, just use as a quick example
int read = raf.read(data);
if (read <= 0) {
// I am still unsure as to return '0', '-1' or 'AVERROR_EOF'.
// But according to the following link, it should return 'AVERROR_EOF',
// http://www.codeproject.com/Tips/489450/Creating-Custom-FFmpeg-IO-Context
// btw 'AVERROR_EOF' is a nasty negative number, '-541478725'.
return AVERROR_EOF;
}
buf.position(0);
buf.put(data, 0, read);
return read;
} catch (Exception ex) {
ex.printStackTrace();
return -1;
}
}
};
Seek_Pointer_long_int seeker = new Seek_Pointer_long_int() {
#Override
public long call(Pointer pointer, long offset, int whence) {
try {
if (whence == AVSEEK_SIZE) {
// Returns the entire file length. If not supported, simply returns a negative number.
// https://www.ffmpeg.org/doxygen/trunk/avio_8h.html#a427ff2a881637b47ee7d7f9e368be63f
return raf.length();
}
raf.seek(offset);
return offset;
} catch (IOException ex) {
ex.printStackTrace();
return -1;
}
}
};
int inputBufferSize = 32768;
BytePointer inputBuffer = new BytePointer(av_malloc(inputBufferSize));
AVIOContext ioContext = avio_alloc_context(inputBuffer,
inputBufferSize,
0, // CRITICAL, if the context is for reading, it should be ZERO
// if the context is for writing, then it is ONE
null,
reader,
null,
seeker);
AVInputFormat format = av_find_input_format("3gp");
AVFormatContext formatContext = avformat_alloc_context();
formatContext.iformat(format);
formatContext.flags(formatContext.flags() | AVFMT_FLAG_CUSTOM_IO);
formatContext.pb(ioContext);
// Now this is working properly.
int result = avformat_open_input(formatContext, "", format, null);
System.out.println("result == " + result);
// all clean-up code omitted for simplicity
}
}
References:
AVSEEK_SIZE documentation
avio_alloc_context() documentation
Additional References: (I do not have enough reputation points for more links but I found these examples critical in helping me so I pasted them in plain text anyway)
Creating Custom FFmpeg IO-Context (CodeProject Example) at:
http://www.codeproject.com/Tips/489450/Creating-Custom-FFmpeg-IO-Context
Another example showing the use of write_flag in avio_alloc_context() at:
https://www.ffmpeg.org/doxygen/2.5/avio_reading_8c-example.html#a20
Your seek code needs to handle AVSEEK_SIZE as whence, and your read should return 0 on EOF ("Upon reading end-of-file, zero is returned." - literal quote from man 2 read), not AVERROR_EOF.

Extract Images from PDF coordinates using iText

I found some examples for how to extract images from PDF using iText. But what I am looking for is to get the images from PDF by coordinates.
Is it possible? If yes then how it can be done.
Along the lines of the iText example ExtractImages you can extract code like this:
PdfReader reader = new PdfReader(resourceStream);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
ImageRenderListener listener = new ImageRenderListener("testpdf");
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
parser.processContent(i, listener);
}
The ImageRenderListener is defined like this:
class ImageRenderListener implements RenderListener
{
final String name;
int counter = 100000;
public ImageRenderListener(String name)
{
this.name = name;
}
public void beginTextBlock() { }
public void renderText(TextRenderInfo renderInfo) { }
public void endTextBlock() { }
public void renderImage(ImageRenderInfo renderInfo)
{
try
{
PdfImageObject image = renderInfo.getImage();
if (image == null) return;
int number = renderInfo.getRef() != null ? renderInfo.getRef().getNumber() : counter++;
String filename = String.format("%s-%s.%s", name, number, image.getFileType());
FileOutputStream os = new FileOutputStream(filename);
os.write(image.getImageAsBytes());
os.flush();
os.close();
PdfDictionary imageDictionary = image.getDictionary();
PRStream maskStream = (PRStream) imageDictionary.getAsStream(PdfName.SMASK);
if (maskStream != null)
{
PdfImageObject maskImage = new PdfImageObject(maskStream);
filename = String.format("%s-%s-mask.%s", name, number, maskImage.getFileType());
os = new FileOutputStream(filename);
os.write(maskImage.getImageAsBytes());
os.flush();
os.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
As you see the ImageRenderListener method renderImage retrieves an argument ImageRenderInfo. This arguments has methods
getStartPoint giving you a vector in User space representing the start point of the xobject and
getImageCTM giving you the coordinate transformation matrix active when this image was rendered. Coordinates are in User space.
The latter gives you the information which exact manipulation on a 1x1 user space unit square are used to actually draw the image. As you are aware, an image may be rotated, stretched, skewed, and moved (the former method actually extracts its result from the matrix from the "moved" information).

Image names are not displaying in the jList

My code is given below.I want to display all the image names into the jList from a folder.But the following code displays the names in the output screen not in the jList.Please help to solve this
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String path = "C:\\Users\\Dell\\Documents\\NetBeansProjects\\pasword2\\src\\images\\";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
DefaultListModel listModel = new DefaultListModel();
int count = 0;
for (int i = 0; i < listOfFiles.length; i++)
{
System.out.println("check path"+listOfFiles[i]);
String name = listOfFiles[i].toString();
// load only JPEGs
if ( name.endsWith("jpg")||name.endsWith("bmp") ) {
try
{
ImageIcon ii = new ImageIcon(ImageIO.read(listOfFiles[i]));
listModel.add(count++, ii);
}
catch(IOException e){}
}
}
jList1.setModel(listModel);
}
You want the file name only to appear in the list, but you're adding the image instead. So instead of
try{
ImageIcon ii = new ImageIcon(ImageIO.read(listOfFiles[i]));
listModel.add(count++, ii);
}
catch(IOException e){}
Just do
listModel.add(count++, listOfFiles[i].getName());
If you want to store the ImageIcon and the file name into one object, you can create a wrapper class. Something like
public class NamedImageIcon {
private String imageName;
private ImageIcon icon;
public NamedImageIcon(ImagIcon icon, String imageName) {
this.icon = icon;
this.imageName = imageName;
}
// getters and setters
#Override
public String toString() {
return imageName;
}
}
No when you're looping you can create a wrapper for the name and for the image. You can then add instances of NamedImageIcon to the DefaultListModel. And since you override the toString(), the only thing that will appear in the list is the name. So when you select the name from the list, you will have direct access the corresponding image

I am trying to use a function that uses FormatWith() and I get an error in C#

I am trying to build an email template. I got what is suppose to be working example but I am having problems trying to get FormatWith() to resolve in one of the functions.
private static string PrepareMailBodyWith(string templateName, params string[] pairs)
{
string body = GetMailBodyOfTemplate(templateName);
for (var i = 0; i < pairs.Length; i += 2)
{
// wonder if I can bypass Format with and just use String.Format
body = body.Replace("<%={0}%>".FormatWith(pairs[i]), pairs[i + 1]);
//body = body.Replace("<%={0}%>",String.Format(pairs[i]), pairs[i + 1]);
}
return body;
}
It looks like an extension method to me.
You need to reference the namespace the extension method lives in at the top of your file.
Example:
namespace MyApp.ExtensionMethods
{
public class MyExtensions
{
public static string FormatWith(this string target, params object[] args)
{
return string.Format(Constants.CurrentCulture, target, args);
}
}
}
...
using MyApp.ExtensionMethods;
...
private static string PrepareMailBodyWith(string templateName, params string[] pairs)
{
string body = GetMailBodyOfTemplate(templateName);
for (var i = 0; i < pairs.Length; i += 2)
{
// wonder if I can bypass Format with and just use String.Format
body = body.Replace("<%={0}%>".FormatWith(pairs[i]), pairs[i + 1]);
//body = body.Replace("<%={0}%>",String.Format(pairs[i]), pairs[i + 1]);
}
return body;
}
Try using String.Format() instead, like you suggested...
body = body.Replace(String.Format("<%={0}%>", pairs[i]), String.Format("<%={0}%>", pairs[i+1]);
This assumes you want both the search string and the replacement string to be formatted.
I found it was easier to use the .Replace() then to jump through all the other hoops. Thank you for your suggestions.
string email = emailTemplate
.Replace("##USERNAME##", userName)
.Replace("##MYNAME##", myName);
This seems to be the simplest solution to my email template issue.

C# Cache of Object is quoting strings

That's something I can't believe, but it's happening.
I have the following code:
public class UserData
{
public string displayname;
public int age;
}
UserData ud = new UserData();
ud.displayname = "bar";
ud.age = 2;
HttpContext.Current.Cache.Insert("foo", ud, null, DateTime.Now.AddMinutes(20), TimeSpan.Zero, CacheItemPriority.Normal, null);
UserData lud = HttpContext.Current.Cache["foo"];
HttpContext.Current.Trace.Write("displayname",ud.displayname);
Guess what is the output?
"bar"
Quoted!!!!
(The int field is not affected, it returned as int, not quoted, etc...)
Why is that? I searched on MSDN and google to no avail.
Use an ashx page to see the output.

Resources