My programm shall communicate via RS232, therefore i use a .jar and two .dll's from RXTX. At the end I want to run it from a single .jar file.
To solve this problem i used this tutorial. But if I run the program from Eclipse (or after exporting from console) I get this exception:
java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "main" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
Here is an minimal example of my code
private static final String LIB = "lib/";
private final static String RXTXPARALLEL = "rxtxParallel";
private final static String RXTXSERIAL = "rxtxSerial";
static {
try {
System.loadLibrary(RXTXSERIAL);
System.loadLibrary(RXTXPARALLEL);
} catch (UnsatisfiedLinkError e) {
loadFromJar();
}
}
public static void main(String[] args) {
//RS232 is this class
RS232 main = new RS232();
main.connect("COM15");
}
private static void loadFromJar() {
String path = "AC_" + new Date().getTime();
loadLib(path, RXTXPARALLEL);
loadLib(path, RXTXSERIAL);
}
private static void loadLib(String path, String name) {
name = name + ".dll";
try {
InputStream in = ResourceLoader.load(LIB + name);
File fileOut = new File(System.getProperty("java.io.tmpdir") + "/"
+ path + LIB + name);
OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();
System.load(fileOut.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
private void connect(String portName) {
CommPortIdentifier portIdentifier;
try {
//Here the exception is thrown
portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
} catch (NoSuchPortException exc) {
exc.printStackTrace();
return;
}
//... some other code
}
Is there a way to get an executable .jar file?
You have a few options. Try to copy the .dll files in the runtime folder and override the files at each start of your program. A second option is to copy the files in a fix folder and add the path of the folder to the environment variables in MS Windows. You can also override the files at each start.
Another possibility is to add the temporary folder to the MS Windows environment variables at runntime. But be careful with this solution, for more information read this post.
static {
try {
System.loadLibrary(RXTXSERIAL);
System.loadLibrary(RXTXPARALLEL);
} catch (UnsatisfiedLinkError exc) {
initLibStructure();
}
}
private static void initLibStructure() {
try {
//runntime Path
String runPath = new File(".").getCanonicalPath();
//create folder
File dir = new File(runPath + "/" + LIB);
dir.mkdir();
//get environment variables and add the path of the 'lib' folder
String currentLibPath = System.getProperty("java.library.path");
System.setProperty("java.library.path",
currentLibPath + ";" + dir.getAbsolutePath());
Field fieldSysPath = ClassLoader.class
.getDeclaredField("sys_paths");
fieldSysPath.setAccessible(true);
fieldSysPath.set(null, null);
loadLib(runPath, RXTXPARALLEL);
loadLib(runPath, RXTXSERIAL);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void loadLib(String path, String name) {
name = name + ".dll";
try {
InputStream in = ResourceLoader.load(LIB + name);
File fileOut = new File(path + "/" + LIB + name);
OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();
System.load(fileOut.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I am working on an application which will download 3rd party dependencies to a particular folder and then execute dependency check on it. The files downloaded can be of any type, they can be zip, jar or may b a folder. I am trying to find a code example but nothing seems to work for me. I tried NIO in java but that seems to work only for writing to a particular file not folder. Below is code where I used NIO
// Checking If The File Exists At The Specified Location Or Not
Path filePathObj = Paths.get(filePath);
boolean fileExists = Files.exists(filePathObj);
if(fileExists) {
try {
urlObj = new URL(sampleUrl);
rbcObj = Channels.newChannel(urlObj.openStream());
fOutStream = new FileOutputStream(filePath);
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
System.out.println("! File Successfully Downloaded From The Url !");
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());
} finally {
try {
if(fOutStream != null){
fOutStream.close();
}
if(rbcObj != null) {
rbcObj.close();
}
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
}
}
} else {
System.out.println("File Not Present! Please Check!");
}```
public Class CopyAndWrite {
public static final String SOURCES = "C:\\Users\\Administrator\\Desktop\\resources";
public static final String TARGET = "C:\\Users\\Administrator\\Desktop\\111";
public static void main (String[]args) throws IOException {
Path startingDir = Paths.get(SOURCES);
Files.walkFileTree(startingDir, new FindJavaVisitor());
}
private static class FindJavaVisitor extends SimpleFileVisitor<Path> {
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (!StringUtils.equals(dir.toString(), SOURCES)) {
Path targetPath = Paths.get(TARGET + dir.toString().substring(SOURCES.length()));
if (!Files.exists(targetPath)) {
Files.createDirectory(targetPath);
}
}
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path targetPath = Paths.get(TARGET + file.toString().substring(SOURCES.length()));
copyFile(targetPath, Files.readAllBytes(file));
return FileVisitResult.CONTINUE;
}
}
private static void copyFile (Path path,byte[] bytes){
// write file
try {
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using OKHttpClient to download the file and place in a folder.
Request request = new Request.Builder().url(downloadUrl).build();
Response response;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
fileName = abc.zip
Path targetPath = new File(inDir + File.separator + fileName).toPath();
try (FileOutputStream fos = new FileOutputStream(targetPath)) {
fos.write(response.body().bytes());
}
return 0;
}
} catch (IOException e) {
logger.error(e.getMessage());
}```
I've a Java program that is copying a file from Unix to hdfs. It is running fine however I am looking for impersonating a different account when it runs and copies file.
Input: Apart form input file and target hdfs directory path, another input should be properties file containing account, keytab directory, domain
Please kindly let me know the best way to move forward.
I am currently exploring using a shell to first issue a kinit command and then run the jar
I am also reading about Jaas and how this can be done in Java itself - from - https://henning.kropponline.de/2016/02/14/a-secure-hdfs-client-example/
Need inputs and any reference of available options.
My Java program that copies file is as below:
public class FileCopy implements Runnable {
#Option(names = {"-i","--input"}, required=true, description="file name to copy to hadoop")
String input;
#Option(names = {"-o","--output"}, required=true, description="hdfs directory path to be copied into")
String output;
public void run() {
Properties hadoop_properties = new Properties();
HdfsFileDeploy hdfsFileDeploy = new HdfsFileDeploy();
try {
hadoop_properties.load(FileCopy.class.getClassLoader().getResourceAsStream("hadoop.properties"));
} catch (IOException e) {
e.printStackTrace();
}
FileSystem fs = hdfsFileDeploy.configureFilesystem(hadoop_properties.getProperty("coreSitePath"),hadoop_properties.getProperty("hdfsSitePath"));
String status = hdfsFileDeploy.writeToHDFS(fs,input,output);
if (status == "SUCCESS") {
System.out.println("completed copying");
} else {
System.out.println("copying error");
}
hdfsFileDeploy.closeFileSystem(fs);
}
public static void main(String[] args) throws IOException {
CommandLine.run(new FileCopy(), args);
}
}
public class HdfsFileDeploy {
public FileSystem configureFilesystem(String coreSitePath, String hdfsSitePath) {
FileSystem fileSystem = null;
try {
Configuration conf = new Configuration();
Path hdfsCoreSitePath = new Path(coreSitePath);
Path hdfsHDFSSitePath = new Path(hdfsSitePath);
conf.addResource(hdfsCoreSitePath);
conf.addResource(hdfsHDFSSitePath);
fileSystem = FileSystem.get(conf);
System.out.println(fileSystem);
return fileSystem;
} catch (Exception ex) {
ex.printStackTrace();
return fileSystem;
}
}
public void closeFileSystem(FileSystem fileSystem) {
try {
fileSystem.close();
} catch (Exception ex) {
System.out.println("Unable to close Hadoop filesystem : " + ex);
}
}
//
public String writeToHDFS(FileSystem fileSystem, String sourcePath, String destinationPath) {
String failure = "FAILURE";
String success = "SUCCESS";
Boolean doNotDelSrc = false;
Boolean overwrite = true;
try {
Path inputPath = new Path(sourcePath);
Path outputPath = new Path(destinationPath);
if(!fileSystem.exists(outputPath)) {
System.out.println("Output path " + outputPath + " does not exist. Creating outputPath directory now..");
if (fileSystem.mkdirs(outputPath)) {
System.out.println("Output path " + outputPath + " created...");
}
}
System.out.println("about to copy from " + inputPath + " to " + outputPath);
fileSystem.copyFromLocalFile(doNotDelSrc, overwrite, inputPath, outputPath);
return success;
} catch (IOException ex) {
System.out.println("Some exception occurred while writing file to hdfs");
ex.printStackTrace();
return failure;
}
}
}
Input1: input file
Input2: target hdfs directory
Reference Input: file (say yaml) containing account, domain, keytab path.
jar should impersonate and copy the input file to target hdfs directory.
I have made the code which renames all the jpg files in a directory from 1 to n (number of files)..
if there were let say 50 jpg files that after running the program all the files are renamed to 1.jpg ,2.jpg and so on till 50.jpg
But i am facing the problem if I manually rename the file let say 50.jpg to aaa.jpg then again running the program doesn't rename that file
I have wasted one day to resove that issue
Kindly help me
Code:
public class Renaming {
private static String path; // string for storing the path
public static void main(String[] args) {
FileReader fileReader = null; // filereader for opening the file
BufferedReader bufferedReader = null; // buffered reader for buffering the data of file
try{
fileReader = new FileReader("input.txt"); // making the filereader object and paasing the file name
bufferedReader = new BufferedReader(fileReader); //making the buffered Reader object
path=bufferedReader.readLine();
fileReader.close();
bufferedReader.close();
}
catch (FileNotFoundException e) { // Exception when file is not found
e.printStackTrace();
}
catch (IOException e) { // IOException
e.printStackTrace();
}
finally {
File directory=new File(path);
File[] files= directory.listFiles(); // Storing the all the files in Array
int file_counter=1;
for(int file_no=0;file_no<files.length;file_no++){
String Extension=getFileExtension(files[file_no]); //getting the filw extension
if (files[file_no].isFile() && (Extension .equals("jpg")|| Extension.equals("JPG"))){ // checking that if file is of jpg type then apply renaming // checking thaat if it is file
File new_file = new File(path+"\\"+files[file_no].getName()); //making the new file
new_file.renameTo(new File(path+"\\"+String.valueOf(file_no+1)+".jpg")); //Renaming the file
System.out.println(new_file.toString());
file_counter++; // incrementing the file counter
}
}
}
}
private static String getFileExtension(File file) { //utility function for getting the file extension
String name = file.getName();
try {
return name.substring(name.lastIndexOf(".") + 1); // gettingf the extension name after .
} catch (Exception e) {
return "";
}
}`
first of all, you should use the path separator / . It's work on Windows, Linux and Mac OS.
This is my version of your problem to rename all files into a folder provide. Hope this will help you. I use last JDK version to speed up and reduce the code.
public class App {
private String path = null;
public static int index = 1;
public App(String path){
if (Files.isDirectory(Paths.get( path ))) {
this.path = path;
}
}
public void rename() throws IOException{
if ( this.path != null){
Files.list(Paths.get( this.path ))
.forEach( f ->
{
String fileName = f.getFileName().toString();
String extension = fileName.replaceAll("^.*\\.([^.]+)$", "$1");
try {
Files.move( f ,Paths.get( this.path + "/" + App.index + "." + extension));
App.index++;
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
}
public static void main(String[] args) throws IOException {
App app = new App("c:/Temp/");
app.rename();
}
}
I am using a Windows machine and Java. I'm just trying to backup a file, but I ran into an issue with an illegal character in the path ("#"). I really tried and I'm stuck. I rewrote it trying all the variations I could find or think of. Any help would be greatly appreciated.
public class SyncActionMachine {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException, URISyntaxException {
String MSI_one, MSI_two, dropBox;
GetDate getDate = new GetDate();
MSI_one = "C:\\Users\\Brian\\AppData\\Roaming\\Macromedia\\Flash Player\\#SharedObjects\\Q2965ZS7\\localhost\\ActionMachine.sol";
MSI_two = "C:\\Users\\Brian\\Desktop\\test.txt";
dropBox = "C:\\Users\\Brian\\Dropbox\\Action Machine History\\ActionMachine.sol";
File source = new File(MSI_one);
File destination = new File(dropBox);
// Attempt #1 using string with special characters
try {
Files.copy(source.toPath(), destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Attempt #2 using URI - not really sure how to use it.
URI uri;
uri = new URI("file:///C:/Users/Brian/AppDate/Roaming/Macromedia/Flash%20Player/%23SharedObjects/Q2965ZS7/localhost/ActionMachine.sol");
Path uriSelfMadePath = Paths.get(uri);
try {
Files.copy(uriSelfMadePath, destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Attempt #3 Suggestion from Aurasphere. Thanks again for quick response.
// Not sure what I'm suppose to do with the URL
String thePath = MSI_one;
thePath = URLEncoder.encode(thePath, "UTF-8");
Path aurasphereThePath = Paths.get(thePath);
try {
Files.copy(aurasphereThePath, destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Attempt #4 build path using Patha and passing in augruments separately
Path pathOneByOne = Paths.get("C:", "Users", "Brian", "AppDate", "Roaming", "Macromedia", "Flash Player",
"#SharedObjects", "Q2965ZS7", "localhost", "ActionMachine.sol");
try {
Files.copy(pathOneByOne, destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Seeing what all these path's look like
URL fileUrl = source.toURI().toURL();
URI fileUri = source.toURI();
System.out.println("------------Path Print out------------------");
System.out.println("URLEncoder : " + thePath);
Path from = Paths.get(fileUri);
System.out.println("URL : " + fileUrl);
System.out.println("URI : " + fileUri);
System.out.println("source: " + source);
}
}
Thanks for any advice.
Just use URLEncode:
String thePath = "your_path";
thePath = URLEncoder.encode(thePath, "UTF-8");
Thank you everyone that looked and commented. Must have been some sleep derived moment. Anyway here is the source, it worked fine. Turned out # was a big deal, I'm not even sure what my hang up was.
public static void main(String[] args) throws IOException, URISyntaxException {
String MSI_one, MSI_two, dropBox;
GetDate getDate = new GetDate();
MSI_one = "C:\\Users\\Brian\\AppData\\Roaming\\Macromedia\\Flash Player\\#SharedObjects\\Q2965ZS7\\localhost\\ActionMachine.sol";
MSI_two = "C:\\Users\\brian\\AppData\\Roaming\\Macromedia\\Flash Player\\#SharedObjects\\HSTARDTM\\localhost\\ActionMachine.sol";
dropBox = "C:\\Users\\brian\\Dropbox\\Action Machine History\\";
// Create new file name for backup file
dropBox = dropBox + "ActionMachine-" + getDate.today() + ".sol";
File source = new File(MSI_two);
File destination = new File(dropBox);
copyNewFile cf = new copyNewFile(source, destination);
}
public class copyNewFile {
public copyNewFile(File source, File dest) throws IOException {
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(source.toPath(), dest.toPath(), options);
System.out.println("File sucessfully copied.");
}
}
I have a program that requires that an internal file (DICTIONARY) be copied to the user's computer into the folder defined like so:
private static final String DIC_NAME = "WordHelp.dic";
private static final String DIC_FOLDER = System.getProperty("user.home");
private static final String PATH_SEP = System.getProperty("file.separator");
public static final String DICTIONARY = DIC_FOLDER + PATH_SEP + DIC_NAME;
Here's what works on MY computer, where all the Java stuff is:
public static void createDictionaryIfNecessary() throws IOException{
Path out_path = FileSystems.getDefault().getPath(DICTIONARY);
boolean dic_exists = Files.exists(out_path,
new LinkOption[]{LinkOption.NOFOLLOW_LINKS});
if(dic_exists)
return;
File file = new File("src/dictionary"); // here's problem for user ************
Path in_path = file.toPath();
try {
Files.copy(in_path, out_path,
REPLACE_EXISTING, COPY_ATTRIBUTES, NOFOLLOW_LINKS);
} catch (IOException e) { JOptionPane.showMessageDialog(null, e); }
}
But user gets this error:
java.nio.file.NoSuchFileException: src\dictionary
SOURCE file (internal to .jar file) can't be found.
If I look at in_path while debugging, the value is:
(sun.nio.fs.Windowspath) src/dictionary
And below is a bunch of info about in_path:
This all works on MY computer and I could have sworn that it ONCE worked on a user's computer...
How should I define file (see line with ********** to enable copying internal file (src/dictionary) onto a user's computer?
Here's Netbeans project view:
I worked around it by using a Scanner to read individual strings from the internal file instead of using Files.copy. Here's the code. (It's not quite as fast using Scanner, but it works.)
public static void write(FileOutputStream outfile, String s) {
try {
for(int i = 0; i < s.length(); i++)
outfile.write(s.charAt(i));
outfile.write(13); outfile.write(10);
} catch (IOException ex) {JOptionPane.showMessageDialog(null, ex);}
}
public static Scanner openDic(){
InputStream myStream = null;
try { myStream = Class.forName("masterwords.Masterwords").getClassLoader()
.getResourceAsStream("dictionary");
}catch (ClassNotFoundException ex) {/* ... */}
return new Scanner(myStream).useDelimiter("\r");
}
public static void createDictionaryIfNecessary(){
Path out_path = FileSystems.getDefault().getPath(DICTIONARY);
if(Files.exists(out_path, new LinkOption[]{LinkOption.NOFOLLOW_LINKS})) return;
FileOutputStream outStream = null;
try {outStream = new FileOutputStream(out_path.toFile());}
catch (FileNotFoundException ex) {JOptionPane.showMessageDialog(null,ex);}
Scanner scInternalDic = IO.openDic();
while(scInternalDic.hasNext()){
Utilities.write(outStream,scInternalDic.next());
}
try {outStream.close();}
catch (IOException ex) {JOptionPane.showMessageDialog(null,ex);}
scInternalDic.close();
}