In iText7, is it possible to create a PdfFont from a classpath font resource*?
Currently, I save the resource to a temporary folder and use
PdfFont font;
public void setFont() {
font = PdfFontFactory.createFont(FontProvider.getFont(), PdfEncodings.IDENTITY_H, true);
}
Where FontProvider.getFont() either returns a path to the classpath file for use in the IDE or saves a file to a temporary folder on the host system and returns a path to this.
If possible, I'd like to avoid the step of saving the file to the host system.
(* an open licensed font)
All static PdfFontFactory::createFont methods also have an overload that requires a byte[] instead of a String. So you'll need to find a way to get your resource into a byte[].
From the resource location, you can create an InputStream. Then you can use a third-party method to get the bytes from that InputStream (e.g.
Convert InputStream to byte array in Java).
InputStream is = this.getClass().getResourceAsStream("/class/path/URI");
byte[] fontBytes = IOUtils.toByteArray(is); // from Apache Commons IO
PdfFontFactory.createFont(fontBytes, PdfEncodings.IDENTITY_H, true);
FYI iText will internally use a similar algorithm to convert a resource referenced by a String to a byte[] for further processing in an IRandomAccessSource.
Related
I want to get the time creation of files in GCS, I used the code below :
println(Files
.getFileAttributeView(Paths.get("gs://datalake-dev/mu/tpu/file.0450138"), classOf[BasicFileAttributeView])
.readAttributes.creationTime)
The problem is that the Paths.get function replace // with / so I will get gs:/datalake-dev/mu/tpu/file.0450138 instead of gs://datalake-dev/mu/tpu/file.0450138.
Anyone can help me with this ?
Thanks a lot !
I solved the problem by adding the following java code and then calling the java function in scala.
import com.google.cloud.storage.*;
import java.sql.Timestamp;
public class ExtractDate {
public static String getTime(String fileName){
String bucketName = "bucket-data";
String blobName = "doc/files/"+fileName;
// Instantiates a client
Storage storage_client = StorageOptions.getDefaultInstance().getService();
Bucket bucket = storage_client.get(bucketName);
//val storage_client = Storage.
BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage_client.get(blobId);
Timestamp tmp = new Timestamp(bucket.get(blobName).getCreateTime());
System.out.print(bucket.get(blobName).getContent());
// return the year of the file date creation
return tmp.toString().substring(0,4);
}
}
You can use the file_get_contents method to read the contents of the path. From the documentation on Reading and Writing Files
Read objects contents using PHP to fetch an object's custom metadata from Google Cloud Storage.An App Engine PHP 5 app must use the Cloud Storage stream wrapper to write files at runtime. However, if an app needs to read files, and these files are static, you can optionally read static files uploaded with your app using PHP filesystem functions such as file_get_contents.
$fileContents = file_get_contents($filePath);
where the path specified must be a path relative to the script accessing them.
You must upload the file or files in an application subdirectory when you deploy your app to App Engine, and must configure the app.yaml file so your app can access those files. For complete details, see PHP 5 Application Configuration with app.yaml.
In the app.yaml configuration, notice that if you use a static file or directory handler (static_files or static_dir) you must specify application_readable set to true or your app won't be able to read the files. However, if the files are served by a script handler, this isn't necessary, because these files are readable by script handlers by default.
AEM6.2
I have a Osgi Service where in org.apache.sling.event.jobs.JobManager referenced and job is added to it.
The code is something like:
Map dataSourceMap = new HashMap<String, DataSource>
dataSourceMap.put(fileName, new ByteArrayDataSource(byte[], mimeTypeOfFile))
final Map<String, Object> props = new HashMap<String, Object>();
props.put("item1", "/something");
props.put("count", 5);
props.put("files", dataSourceMap)
jobManager.addJob("my/special/jobtopic", props);
When this job gets executed it shows some error
org.apache.sling.api.resource.PersistenceException: Value can't be stored in the repository: {<<filename>>=org.apache.commons.mail.ByteArrayDataSource#3f0f234c}
Question: Is there any solution to this exception? Or am I doing something wrong? can we add a ByteArrayInputStream to the jobmanager?
Thank you !
Just a info, If I remove the line props.put("files", dataSourceMap), it works fine.
Please let me know if you need more info on it.
Sling will store the job as a node in the repository and it looks like it only supports the "standard" types like String, Boolean, Integer etc. and not files/blobs.
I can not think of a way to add a file to the job, but what you could do is to create temporary node in the repository yourself, which contains the files/blobs.
Sling stores jobs here:
/var/eventing/jobs
You might do something similar:
/var/<project-name>/jobs
And the payload of the Sling job then contains the path to this job node.
Further to Jens' comment, the job will indeed store data as node properties in the JCR. You could likely explore the possibility of storing data as Binary to the jcr:data property, but I have not tested this myself.
As a quick and likely not very optimized workaround, why not serialize your byte[] to a String or even encode it to a Base64 string?
Sample: Base64 Java encode and decode a string [duplicate]
How can I change the current working directory from within a Java program? Everything I've been able to find about the issue claims that you simply can't do it, but I can't believe that that's really the case.
I have a piece of code that opens a file using a hard-coded relative file path from the directory it's normally started in, and I just want to be able to use that code from within a different Java program without having to start it from within a particular directory. It seems like you should just be able to call System.setProperty( "user.dir", "/path/to/dir" ), but as far as I can figure out, calling that line just silently fails and does nothing.
I would understand if Java didn't allow you to do this, if it weren't for the fact that it allows you to get the current working directory, and even allows you to open files using relative file paths....
There is no reliable way to do this in pure Java. Setting the user.dir property via System.setProperty() or java -Duser.dir=... does seem to affect subsequent creations of Files, but not e.g. FileOutputStreams.
The File(String parent, String child) constructor can help if you build up your directory path separately from your file path, allowing easier swapping.
An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.
The relevant OpenJDK bug was closed in 2008 as "will not fix".
If you run your legacy program with ProcessBuilder, you will be able to specify its working directory.
There is a way to do this using the system property "user.dir". The key part to understand is that getAbsoluteFile() must be called (as shown below) or else relative paths will be resolved against the default "user.dir" value.
import java.io.*;
public class FileUtils
{
public static boolean setCurrentDirectory(String directory_name)
{
boolean result = false; // Boolean indicating whether directory was set
File directory; // Desired current working directory
directory = new File(directory_name).getAbsoluteFile();
if (directory.exists() || directory.mkdirs())
{
result = (System.setProperty("user.dir", directory.getAbsolutePath()) != null);
}
return result;
}
public static PrintWriter openOutputFile(String file_name)
{
PrintWriter output = null; // File to open for writing
try
{
output = new PrintWriter(new File(file_name).getAbsoluteFile());
}
catch (Exception exception) {}
return output;
}
public static void main(String[] args) throws Exception
{
FileUtils.openOutputFile("DefaultDirectoryFile.txt");
FileUtils.setCurrentDirectory("NewCurrentDirectory");
FileUtils.openOutputFile("CurrentDirectoryFile.txt");
}
}
It is possible to change the PWD, using JNA/JNI to make calls to libc. The JRuby guys have a handy java library for making POSIX calls called jnr-posix. Here's the maven info
As mentioned you can't change the CWD of the JVM but if you were to launch another process using Runtime.exec() you can use the overloaded method that lets you specify the working directory. This is not really for running your Java program in another directory but for many cases when one needs to launch another program like a Perl script for example, you can specify the working directory of that script while leaving the working dir of the JVM unchanged.
See Runtime.exec javadocs
Specifically,
public Process exec(String[] cmdarray,String[] envp, File dir) throws IOException
where dir is the working directory to run the subprocess in
If I understand correctly, a Java program starts with a copy of the current environment variables. Any changes via System.setProperty(String, String) are modifying the copy, not the original environment variables. Not that this provides a thorough reason as to why Sun chose this behavior, but perhaps it sheds a little light...
The working directory is a operating system feature (set when the process starts).
Why don't you just pass your own System property (-Dsomeprop=/my/path) and use that in your code as the parent of your File:
File f = new File ( System.getProperty("someprop"), myFilename)
The smarter/easier thing to do here is to just change your code so that instead of opening the file assuming that it exists in the current working directory (I assume you are doing something like new File("blah.txt"), just build the path to the file yourself.
Let the user pass in the base directory, read it from a config file, fall back to user.dir if the other properties can't be found, etc. But it's a whole lot easier to improve the logic in your program than it is to change how environment variables work.
I have tried to invoke
String oldDir = System.setProperty("user.dir", currdir.getAbsolutePath());
It seems to work. But
File myFile = new File("localpath.ext");
InputStream openit = new FileInputStream(myFile);
throws a FileNotFoundException though
myFile.getAbsolutePath()
shows the correct path.
I have read this. I think the problem is:
Java knows the current directory with the new setting.
But the file handling is done by the operation system. It does not know the new set current directory, unfortunately.
The solution may be:
File myFile = new File(System.getPropety("user.dir"), "localpath.ext");
It creates a file Object as absolute one with the current directory which is known by the JVM. But that code should be existing in a used class, it needs changing of reused codes.
~~~~JcHartmut
You can use
new File("relative/path").getAbsoluteFile()
after
System.setProperty("user.dir", "/some/directory")
System.setProperty("user.dir", "C:/OtherProject");
File file = new File("data/data.csv").getAbsoluteFile();
System.out.println(file.getPath());
Will print
C:\OtherProject\data\data.csv
You can change the process's actual working directory using JNI or JNA.
With JNI, you can use native functions to set the directory. The POSIX method is chdir(). On Windows, you can use SetCurrentDirectory().
With JNA, you can wrap the native functions in Java binders.
For Windows:
private static interface MyKernel32 extends Library {
public MyKernel32 INSTANCE = (MyKernel32) Native.loadLibrary("Kernel32", MyKernel32.class);
/** BOOL SetCurrentDirectory( LPCTSTR lpPathName ); */
int SetCurrentDirectoryW(char[] pathName);
}
For POSIX systems:
private interface MyCLibrary extends Library {
MyCLibrary INSTANCE = (MyCLibrary) Native.loadLibrary("c", MyCLibrary.class);
/** int chdir(const char *path); */
int chdir( String path );
}
The other possible answer to this question may depend on the reason you are opening the file. Is this a property file or a file that has some configuration related to your application?
If this is the case you may consider trying to load the file through the classpath loader, this way you can load any file Java has access to.
If you run your commands in a shell you can write something like "java -cp" and add any directories you want separated by ":" if java doesnt find something in one directory it will go try and find them in the other directories, that is what I do.
Use FileSystemView
private FileSystemView fileSystemView;
fileSystemView = FileSystemView.getFileSystemView();
currentDirectory = new File(".");
//listing currentDirectory
File[] filesAndDirs = fileSystemView.getFiles(currentDirectory, false);
fileList = new ArrayList<File>();
dirList = new ArrayList<File>();
for (File file : filesAndDirs) {
if (file.isDirectory())
dirList.add(file);
else
fileList.add(file);
}
Collections.sort(dirList);
if (!fileSystemView.isFileSystemRoot(currentDirectory))
dirList.add(0, new File(".."));
Collections.sort(fileList);
//change
currentDirectory = fileSystemView.getParentDirectory(currentDirectory);
I changed a file in Orbeon Forms, and the next time I load the page, I get an error message saying Invalid byte 2 of a 3-byte UTF-8 sequence. How can I solve this problem?
This happens when Orbeon Forms reads an XML file and expects it to use the UTF-8 encoding, but somehow the file isn't properly encoded in UTF-8. To solve this, make sure that:
You have an XML declaration at the beginning of the file saying the file is in UTF-8:
<?xml version="1.0" encoding="UTF-8" ?>
Your editor is XML-aware, so it can parse the XML declaration and consequently use the UTF-8 encoding. If your editor isn't XML aware, and you don't want to use another editor, look for an option or preference allowing you to specify that the editor must use UTF-8.
A three byte UTF-8 sequence looks like:
1110xxxx 10xxxxxx 10xxxxxx
Your error message may mean that the first byte of the three is incorrectly flagging the start of a three byte sequence or else that the second byte is malformed.
As #avernet says, you need to make sure that all elements in your system are producing and expecting UTF-8.
When you start your program, use the following Java command line argument:
-Dfile.encoding=UTF-8
For example,
java -Dfile.encoding=UTF-8 -jar foo.jar
I got the same problem in Eclipse, I just tried by changing the file type.
Right click on file -> Resource -> Text file encoding (UTF-8)
This solution worked for me.
Thanks.
I am using Eclipse and I also had to change the Text file encoding in:
->Windows->Preferences->Workspace
Then it worked fine.
Thanks
You might need to configure your Tomcat with the following parameter:
-Dfile.encoding=UTF-8
Had same problem.
Problem > I'm getting X509 certificate values (multiple encoding source) to generate a PDF report.
The PDF is generated throught a webservice that waits for an UTF-8 xml request and I've to reencode the values before marshalling.
Solution >
http://fabioangelini.wordpress.com/2011/08/04/converting-java-string-fromto-utf-8/
Using this class:
public class StringHelper {
// convert from UTF-8 -> internal Java String format
public static String convertFromUTF8(String s) {
String out = null;
try {
out = new String(s.getBytes("ISO-8859-1"), "UTF-8");
} catch (java.io.UnsupportedEncodingException e) {
return null;
}
return out;
}
// convert from internal Java String format -> UTF-8
public static String convertToUTF8(String s) {
String out = null;
try {
out = new String(s.getBytes("UTF-8"), "ISO-8859-1");
} catch (java.io.UnsupportedEncodingException e) {
return null;
}
return out;
}
}
Usage:
//getSummaryAttMap() returns a HashMap
String value = (String) getSummaryAttMap().get(key);
if(value != null)
value = StringHelper.convertToUTF8(value);
else
value = "";
I'll provide a special coding answer. When you check the xml file and there's nothing wrong, and you're using Java and running Tomcat Server. Your source code may neglect specify the encoding yourself, and thus JVM uses default encoding when read in xml contents as string or something else that repesents string, which in turn refer to Tomcat's default encoding. If encoding of xml and Tomcat are inconsistent, it might also report same error message.
The switching of the encoding for the input might help:
XMLEventReader eventReader =
inputFactory.createXMLEventReader(in,
"utf-8"
//"windows-1251"
);
In my RCP app, I would like to point a property (osgi.java.profile) to a file, and would prefer using paths relative to my installation and config dir.
Is there a definitive spec on what kind of variables are supported in config.ini?
#config.dir seems to be supported, there are references in the builtin, and it's always mentioned as typical example (e.g this SO answer )
However, looking at docs like Eclipse help/Runtime Options, it mentions a few "symbolic locations" like #user.home; however that seems fairly limited and doesn't include #config.dir.
Have even dug into org.eclipse.osgi sources as well, and found no references to this (I did find LocationManager and its hard coded variable substitutions for #user.dir & co).
Can I refer to arbitrary system properties there in some way?
Is this #config.dir a special case, only handled by P2? UPDATE: this seems to be the case.. looking at Eclipse SDK, About .. Configuration dialog shows #config.dir unresolved, probably taken literally by the Equinox..
Thanks for any hints.
I'm late to the party, but hopefully this will help others in the future.
Starting with Eclipse 3.8/4.2 (June 2012), you can substitute Java properties and environment variables into your config.ini file (Eclipse Bug 241192). The Equinox launcher does not support substitution in the eclipse.ini launcher file. The syntax uses dollar signs ($VARIABLE$) to indicate variable substitution:
osgi.configuration.area=$APPDATA$/MyCompany/MyProgram/configuration
osgi.user.area=$APPDATA$/MyCompany/MyProgram/user
osgi.instance.area=$APPDATA$/MyCompany/MyProgram/instance
I imagine you could use something like this for your purposes:
osgi.java.profile=$osgi.install.area$/path/to/profile.txt
You can use a platform URL (Platform URI scheme) to achieve this, i.e.
osgi.java.profile = platform:/config/java_profile.txt
in config.ini, would point to the file java_profile.txt in the current configuration directory.
You might also use existing system properties in config.ini:
osgi.java.profile = ${osgi.configuration.area}/java_profile.txt
From org.eclipse.core.runtime.adaptor.LocationManager, here are the special tokens:
// Data mode constants for user, configuration and data locations.
private static final String NONE = "#none"; //$NON-NLS-1$
private static final String NO_DEFAULT = "#noDefault"; //$NON-NLS-1$
private static final String USER_HOME = "#user.home"; //$NON-NLS-1$
private static final String USER_DIR = "#user.dir"; //$NON-NLS-1$
Why not use two system property variables?
One is named -Dmy.relativepath=filename, which is processed by your code of relative path of eclipse installation folder(workspace or anywhere), another is called -Dmy.path=absolutepath.
The system property is passed to the jvm, you need some tricky(translate the variable in runtime) in the native launcher(like eclipse.exe) if you wants to use variable in its value.
Look how osgi.java.profile is resolved in org.eclipse.osgi.framework.internal.core.Framework:
// check for the java profile property for a url
String propJavaProfile = FrameworkProperties.getProperty(Constants.OSGI_JAVA_PROFILE);
if (propJavaProfile != null)
try {
// we assume a URL
url = new URL(propJavaProfile);
} catch (MalformedURLException e1) {
// try using a relative path in the system bundle
url = findInSystemBundle(propJavaProfile);
}
That means osgi.java.profile must point either to a fully qualified URL, or to a relative path in system bundle (org.eclipse.osgi). This makes impossible usage of installation directory relative path without patching Eclipse.