I have a problem to update a pdf file with arabic text annotation
the pdf has been changed ( size has been changed)
and when I try to open the pdf with acrobat reader the text annotation is not displayed
and when I try to change the fill color of the annotation it has been displayed
I use this code in angular
const blob = new Blob([content], { type: "application/pdf ; charset=utf-8" });
const reader = new FileReader();
reader.readAsDataURL(blob); this.formData.append('files', blob,fileName);
and I use this java code to update the pdf file
public String storeFile(MultipartFile file) {
// Normalize file name
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// Check if the file's name contains invalid characters
if(fileName.contains("..")) {
throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
// Copy file to the target location (Replacing existing file with the same name)
Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
//add owners permission
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OWNER_EXECUTE);
Path targetLocation = this.fileStorageLocation.resolve(fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (IOException ex) {
throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
}
}
Related
I have a JFileChooser and I want to set the directory it opens using some information stored in a .txt file (I'm using a .txt file to persist the desired location between sessions). I can get the file, read the data and set it to a string, but when I try to use that string to set the directory I want to open it doesn't work. My code is roughly something like this:
//buffer contains a byte[] for "/Users/user/Documents/Work/folderToOpen"
desiredPath = new String(buffer);
jFileChooser1.setCurrentDirectory(new java.io.File(desiredPath));
After stepping through this, however, the current directory is set to /Users/user.
If anyone has any ideas about what I'm doing wrong or a better way to accomplish this I'd love to hear it.
Thank you
private static String LAST_FOLDER_USED = null;
//Get the desired file path for user preferences
String pluginRoot = System.getProperty("user.dir") + File.separator.toString();
//Create a file using the desired file Path
File userPreferences = new File(pluginRoot + File.separator + "UserPreferences.txt");
//Get a file called UserPreferences.txt from target/classes to create an input stream
String fileName = "UserPreferences.txt";
InputStream readInFile = getClass().getResourceAsStream(fileName);{
//Convert input stream to read from the desired file in the plug-in root ("filePath" Created Above)
try{
readInFile = new FileInputStream(userPreferences);
}
catch (IOException e){
e.printStackTrace();
}}
//Read the readInFile into a byte[]
String desiredPathToOpenImage;
byte[] buffer = new byte[1000];
int i = 0;{
try {
while((i = readInFile.read(buffer)) !=-1){
System.out.println(new String(buffer));
i++;
}}
catch (IOException e) {
e.printStackTrace();
};
//Convert byte[] to string (This should be the path to the desired folder when selecting an image)
desiredPathToOpenImage = new String(buffer);
}
//Create a New File using the desired path
File desiredPath = new File(desiredPathToOpenImage + File.separator + "prefs.txt");
public SelectImage(Viewer parent, boolean modal) {
super(parent, modal);
initComponents();
int returnVal = jFileChooser1.showOpenDialog(parent);
// Sets up arrays for storing file information to be passed back to the viewer class.
String[] filePath = new String[jFileChooser1.getSelectedFiles().length];
String[] fileName = new String[jFileChooser1.getSelectedFiles().length];
String[] fileDir = new String[jFileChooser1.getSelectedFiles().length];
if (returnVal == JFileChooser.APPROVE_OPTION) {
// Cycles through the selected files and stores each piece accordingly
for (int i = 0; i < jFileChooser1.getSelectedFiles().length; i++) {
File file = jFileChooser1.getSelectedFiles()[i];
filePath[i] = file.getPath();
fileName[i] = file.getName();
fileDir[i] = file.getParent();
}
}
parent.setFilePath(filePath, fileName, fileDir);
}
private void initComponents() {
jFileChooser1 = new javax.swing.JFileChooser();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jFileChooser1.setMultiSelectionEnabled(true);
//Checks folder_Path to see if a value is present. If value is present sets jFileChooser Directory to that value
if(desiredPathToOpenImage.contains(File.separator)){
//Create a File using the desired path for selecting images
//****Currently doesn't set the Directory correctly****//
jFileChooser1.setCurrentDirectory(desiredPath);
}
//If no value is present in LAST_FOLDER_USED sets jFileChooser Directory to desktop
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
//After file is selected sets value of LAST_FOLDER_USED to the absolute path of that file
LAST_FOLDER_USED = jFileChooser1.getCurrentDirectory().toString() + File.separator + "UserPreferences.txt";
try {
FileWriter fileWriter = new FileWriter(userPreferences);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(jFileChooser1.getCurrentDirectory().toString());
OutputStream outPut = new FileOutputStream(pluginRoot + File.separator + "UserPreferences.txt");
outPut.write(LAST_FOLDER_USED.getBytes());
outPut.close();
bufferedWriter.close();
} catch (IOException e) {
System.out.println("Error Writing to File" + desiredPathToOpenImage);
e.printStackTrace();
}
}
});
I think the directory passed as argument does not exist or is not accessible to the user you are logged in with judging from the javadoc of setCurrentDirectory():
If the file passed in as currentDirectory is not a directory, the parent of the file will be used as the currentDirectory. If the parent is not traversable, then it will walk up the parent tree until it finds a traversable directory, or hits the root of the file system.
Make sure all folders in the given path exist and are accessible to the logged user (on linux the 'executable' bit controls the accessibility of a directory). So if you see something like
-d x Documents
after executing
ls -l *
in a shell then the Documents directory is accessible.
Found a better way to accomplish my goal using Preferences instead of trying to create and access files to store the location.
Preferences prefs = Preferences.userNodeForPackage(this.getClass());
static String LAST_FOLDER_USED = "LAST_FOLDER_USED";
String folder_Location;
and then inside initComponents()
if(LAST_FOLDER_USED != null){
jFileChooser1.setCurrentDirectory(new File(prefs.get(LAST_FOLDER_USED, LAST_FOLDER_USED)));
}
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
folder_Location = jFileChooser1.getCurrentDirectory().toString();
prefs.put(LAST_FOLDER_USED, folder_Location);
//System.out.println(prefs.get(LAST_FOLDER_USED, folder_Location));
}
});
I have to find the original content type(MIME Type) of a file at the time of Uploading.
I want to allow only PDF files, But if i am renaming an .exe fiel to .pdf flie, its type is showing pdf.
I want to restrict these kind of files.
I am using the following code:
if (!fileMultipart.getContentType().equalsIgnoreCase("application/pdf")) {
msg = "Only pdf files are allowed.";
System.out.println("Only pdf files are allowed.");
}
Also some online tools are available to find the original content type. I tried using http://www.checkfiletype.com/ and it works.
The file content type is determined by the user-agent/browser on upload. As you already know, this can be spoofed, or incorrect. There really isn't more you can do with just the file's content type.
An alternative is to do more checking after you have verified the content type by attempting to open the PDF for reading using iText, PDFBox, or some similar library. If you can't open the file then you can let the user know there's a problem with it.
public boolean isPDF(String fileName) {
File file = new File(fileName);
System.out.println("file upload isExist " + file.exists());
boolean result = false;
//Scanner input = null;
try {
Scanner input = new Scanner(new FileReader(file));
System.out.println("fileScanner input " + input);
while (input.hasNextLine()) {
final String checkline = input.nextLine();
if (checkline.contains("%PDF-")) {
// a match!
result = true;
break;
}
}
} catch (FileNotFoundException ex) {
System.out.println("file upload is not valid " + file);
Logger.getLogger(UploadContractorFile.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("file upload final result " + result);
return result;
}
About Google Drive, in this Document, Google says there are 3 types of uploadType:
We have the media, multipart and resumable, as it says in the image above.
Also, in the same Document mentioned, Google give a example on Java, explaining how to upload an File into Google Drive.
public class MyClass {
private static File insertFile(Drive service, String title, String description,
String parentId, String mimeType, String filename) {
// File's metadata.
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
// Set the parent folder.
if (parentId != null && parentId.length() > 0) {
body.setParents(
Arrays.asList(new ParentReference().setId(parentId)));
}
// File's content.
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
// Uncomment the following line to print the File ID.
// System.out.println("File ID: " + file.getId());
return file;
} catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
// ...
}
I want to set an Optional Query Parameter, as explained in the image. I can't find how to set the ocr and ocrLanguage in the java SDK of Google Drive. The example of upload above, don't have this parameter to set, also, is not clear what uploadType this java example uses to Upload.
You can use generic set property method
File body = new File();
body.setTitle(title);
body.set("ocr",true);
body.set("ocrLanguage", "zh");
I'm trying to copy some preloaded content stored in the assets folder of my app to the sdk card. Problem is I cant seem to get hold of the file path to the directory I want to copy. I want to loop through the preloadedcontent folder stored in my assets folder in the project, then copy each folder inside it across to the sdk card. I can loop through the preloaded content file names ok, but get a filenotfound exception when i try to copy the directory across:
- Assets/
-- preloadedcontent/
--- 112/
--- 113/
--- 114/
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("preloadedcontent");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
Log.d("file: ",filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("preloadedcontent/" + filename + "/");
File outFile = new File(_DirectoryName, filename);
out = new FileOutputStream(outFile);
//copyFile(in, out);
File f = stream2file(in,filename);
copyDirectory(f,outFile);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
error is on this line assetManager.open("preloadedcontent/" + filename + "/");
That's because "preloadedcontent/" + filename + "/" is not a valid file name (due to the trailing slash).
AssetManager#open() requires the name of a single file to open.
if(id.equals("AABA / ABO")){
AssetManager assetManager = activity.getAssets();
String[] files;
try {
files = assetManager.list("aaba");
List<String> it = Arrays.asList(files);
for (String string : it) {
InputStream ims = assetManager.open("aaba/" + string);
// create drawable from stream
Drawable d = Drawable.createFromStream(ims, null);
drawable.add(d);
}
} catch (IOException e) {
e.printStackTrace();
}
}
I specified the full path of the file location when I created a FileWriter, but I did not see the file being created. I also did not get any error during file creation.
Here's a snippet of my code:
public void writeToFile(String fullpath, String contents) {
File file = new File(fullpath, "contents.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
bw.write(contents);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
fullpath is "D:/codes/sources/logs/../../bin/logs".
I have searched my whole directory, but I cannot find the file anywhere.
If I specify just the filename only [File file = new File("contents.txt");] , it is able to save the contents of the file, but it is not placed on my preferred location.
How can I save the file content to a preferred location?
UPDATE:
I printed the full path using file.getAbsolutePath(), and I am getting the correct directory path. [D:\codes\sources\logs....\bin\logs\contents.txt] But when I look for the file in directory, I cannot find it there.
Make sure you add trailing backslashes to the path parameter so the path is recognized as a directory. The example provide is for a Windows OS which uses backslashes that are escaped. For a more robust method use the file.separator property for the system.
Works
writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development\\",
"this is a test");
Doesn't Work
writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development",
"this is a test");
File Separator Example
String fs = System.getProperty("file.separator");
String path = fs + "Documents and Settings" + fs + "me" + fs
+ "Desktop" + fs + "Development" + fs;
writeToFile(path, "this is a test");