Java jar executable cannot read excel files on dropbox - java

A bit complex issue.
I have a program to read data from excel files using XSSFSheets. Everything works fine.
The problem i have is that for some users the program does not work if the files is located on dropbox. (Local version of dropbox, on their hard drive.)
The issue is not path related. Checked more times than i can count.
What is strange is that everyone has exactly the same admin rights for dropbox and office 365. The only difference i can find so far is that these users has windows 10.
If we place these excel files on the desktop, the program can find them.
Does anyone know if there is an issue for Java get excel sheets on dropbox for any reason? Can it have anything to do with windows 10 resp windows 8? If so why does it work on the windows 10 desktop.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JFrame;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class xlmsReader {
public static ArrayList<XSSFSheet> fileReader() {
String directPath = System.getProperty("user.dir");
//removing the folder name, search through all folders in the parent folder, regardless of the location of the program folder.
directPath = directPath.substring(0, directPath.length()-18);
File[] directories = new File(directPath).listFiles(File::isDirectory);
ArrayList<XSSFSheet> excel = new ArrayList<XSSFSheet>();
for (int j = 0; j < directories.length; j++) {
if (new File(directories[j] + "\\Groning.xlsm").exists()) {
String str = directories[j] + "\\Groning.xlsm";
FileInputStream file;
file = null;
try {
file = new FileInputStream(new File(str));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XSSFWorkbook workbook;
workbook = null;
try {
workbook = new XSSFWorkbook(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XSSFSheet sheet = workbook.getSheet("Gröning");
sheet.getRow(0).getCell(0).setCellValue(directories[j].getPath());
excel.add(sheet);
}
}
return excel;
}
}

Hi everyone that answered.
I finally found out what was wrong.
The computors that run just Java JRE could not run the program.
Computors that ran Java JDK could. So it seems that i have used some function only available for developers. I dont know what exactly but issue solved, so I'm not going to put more effort to it.

Related

How to get java program read it's internal path to make it work on every PC

I'm trying to configure path in code to my excel file to make it work on every computer that i have source code on for example:
my actual file is in com/company/resources/DatabaseLogonData.xlsx
but im trying to open it from class that is in com/company/Database/DatabaseConnection.java
I suppose i have to go back somehow to com/company and then go to the Database package but don't know how
package com.company.Database;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.File;
import java.io.IOException;
import java.sql.*;
public class DatabaseConnection {
private static Database localDatabase;
public static void setLocalDatabaseFromFile()
throws IOException, InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new File(
"C:\\Users\\Wiktor\\IdeaProjects\\mixer\\src\\com\\company\\resources\\DatabaseLogonData.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
Row dataRow = sheet.getRow(1);
localDatabase = new Database(dataRow.getCell(0).getStringCellValue(),
dataRow.getCell(1).getStringCellValue(),
dataRow.getCell(2).getStringCellValue(),
dataRow.getCell(3).getStringCellValue());
}
I want to get path that will work on any pc. Thanks for any feedback !
Use java.nio in order to find out where the code is executed:
public static void main(String args[]) throws Exception {
Path cwd = Paths.get("").toAbsolutePath();
Path parentOfCwd = Paths.get("").toAbsolutePath().getParent();
System.out.println(cwd.toAbsolutePath().toString()
+ " in folder " + parentOfCwd.toAbsolutePath().toString());
}
I don't know if this is best practice for your use case, but you could as well go the way many programs are going and just determine the user.home (see comments below your question), create a folder and store the logs there.

create .gitignore with java

I'm aware this question might be a duplicate in some sense but first hear me out.
I tried to create a code where i can create gitignore file with contents and for some reason i always end up having a file with txt extension and without name. Can someone explain this behavior and why?
Example Code:
System.out.println(fileDir+"\\"+".gitignore");
FileOutputStream outputStream = new FileOutputStream(fileDir+"\\"+".gitignore",false);
byte[] strToBytes = fileContent.getBytes();
outputStream.write(strToBytes);
outputStream.close();
You can use java.nio for it. See the following example:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class StackoverflowMain {
public static void main(String[] args) {
// create the values for a folder and the file name as Strings
String folder = "Y:\\our\\destination\\folder"; // <-- CHANGE THIS ONE TO YOUR FOLDER
String gitignore = ".gitignore";
// create Paths from the Strings, the gitignorePath is the full path for the file
Path folderPath = Paths.get(folder);
Path gitignorPath = folderPath.resolve(gitignore);
// create some content to be written to .gitignore
List<String> lines = new ArrayList<>();
lines.add("# folders to be ignored");
lines.add("**/logs");
lines.add("**/classpath");
try {
// write the file along with its content
Files.write(gitignorPath, lines);
} catch (IOException e) {
e.printStackTrace();
}
}
}
It creates the file on my Windows 10 machine without any problems. You need Java 7 or higher for it.

SFNTLY: How to convert any font that gets uploaded to "WOFF" format?

I can not find any documenration on this library (https://code.google.com/p/sfntly/). I've been taking stabs at it for 2 days now. I'm trying to convert any font that gets uploaded to "WOFF" format.
Could someone shed some light?
I successfully converted my TTF into a WOFF file by following these steps:
Download and install ant following "The Short Story" steps (http://ant.apache.org/manual/install.html#getBinary)
Download SFNTLY via SVN checkout (https://code.google.com/p/sfntly/source/checkout) and followed the steps contained into the file "sfntly\java\quickstart.txt"
Created a new java project and imported the following four jars I created following the previous steps into my project:
sfntly.jar
woffconverter.jar
guava-16.0.1.jar
I slightly tweaked display_name code which contained a few syntax mistakes.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.google.common.io.Files;
import com.google.typography.font.sfntly.Font;
import com.google.typography.font.sfntly.FontFactory;
import com.google.typography.font.sfntly.data.WritableFontData;
import com.google.typography.font.tools.conversion.woff.WoffWriter;
public class Main {
public static void main(String[] args) {
WoffWriter ww = new WoffWriter();
FontFactory fontFactory = FontFactory.getInstance();
byte[] bytes;
try {
bytes = Files.toByteArray(new File("C:\\FontName.TTF"));
Font font = fontFactory.loadFonts(bytes)[0];
WritableFontData wfd = ww.convert(font);
FileOutputStream fs = new FileOutputStream("out.fnt");
wfd.copyTo(fs);
fs.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
After reading the source code of SFNTLY I am no expert in sfntly, so use my answer at your risk :).
I would convert the font with WoffWriter#convert() to writeable font data, then copy the wfd to outputstream.
WoffWriter ww = new WoffWriter();
WriteableFontData wfd = ww.convert(yourFont);
try {
FileOutPutStream fs = new FileOutputStream("out.fnt");
wfd.copyTo(fs, wfd);
fs.close();
} catch (IOException e) {
}

java flickr and flickrj download user pictures

Hi I am new to flickrj library.
Have foundational java knowledge though.
The project that I am working on requires me to authenticate into flickr and then download geo-tagged images into a folder in local hard drive. The program will be Desktop application program.
I am approaching the program by breaking down into 3 steps.
1.Proper authentication to be completed.(which i have succeeded)
2.Try to download all the photos that user has when authenticated.
3.Try to alter the code a little so that it will only download geo-tagged images.
My problems is on step 2. I cant download logged-in user images let alone geo-tagged ones.
I am trying the code provided by Daniel Cukier here
But I am running into problem.
My netbeans simply strike off at the line 77 on .getOriginalAsStream() part, with the error "java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.io.ByteArrayOutputStream.write"
From my understanding netbeans striking off a line means , it is depreciated but shouldnt it still work? What is holding this whole problem back?
I have tried researching and basically I have to admit , it is beyond my capability to trouble shoot. If anyone has any idea on what i am doing wrong , I would be so grateful.
Ps: I am not looking to be spoon fed but please answer me in idiot-friendly way as I am still a student and my java isn't the greatest.
This code is what I have so far.
import com.aetrion.flickr.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.util.IOUtilities;
import java.io.*;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
public class authenticate {
Flickr f;
RequestContext requestContext;
String frob = "";
String token = "";
Properties properties = null;
public authenticate() throws ParserConfigurationException, IOException, SAXException {
InputStream in = null;
try {
in = getClass().getResourceAsStream("/setup.properties");
properties = new Properties();
properties.load(in);
} finally {
IOUtilities.close(in);
}
f = new Flickr(
properties.getProperty("apiKey"),
properties.getProperty("secret"),
new REST()
);
Flickr.debugStream = false;
requestContext = RequestContext.getRequestContext();
AuthInterface authInterface = f.getAuthInterface();
try {
frob = authInterface.getFrob();
} catch (FlickrException e) {
e.printStackTrace();
}
System.out.println("frob: " + frob);
URL url = authInterface.buildAuthenticationUrl(Permission.DELETE, frob);
System.out.println("Press return after you granted access at this URL:");
System.out.println(url.toExternalForm());
BufferedReader infile =
new BufferedReader ( new InputStreamReader (System.in) );
String line = infile.readLine();
try {
Auth auth = authInterface.getToken(frob);
System.out.println("Authentication success");
// This token can be used until the user revokes it.
System.out.println("Token: " + auth.getToken());
System.out.println("nsid: " + auth.getUser().getId());
System.out.println("Realname: " + auth.getUser().getRealName());
System.out.println("Username: " + auth.getUser().getUsername());
System.out.println("Permission: " + auth.getPermission().getType());
PhotoList list = f.getPhotosetsInterface().getPhotos("72157629794698308", 100, 1);
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Photo photo = (Photo) iterator.next();
File file = new File("/tmp/" + photo.getId() + ".jpg");
ByteArrayOutputStream b = new ByteArrayOutputStream();
b.write(photo.getOriginalAsStream());
FileUtils.writeByteArrayToFile(file, b.toByteArray());
}
} catch (FlickrException e) {
System.out.println("Authentication failed");
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
authenticate t = new authenticate();
} catch(Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
You are correct in your interpretation of the strikeout that getOriginalAsStream() is deprecated. It looks like you might want to rework your code to use PhotosInterface.getImageAsStream(), passing the ORIGINAL size as one of the arguments.
To adjust NetBeans' behavior with respect to deprecated methods, you can follow the link recommended by #AljoshaBre as well as this one.
If you want download all your photos from Flickr, this is possible if you have a mac computer.
Download Aperture program on Apple Store and install it.
After to install, open the Aperture.
Go on preferences.
Click on 'Accounts' tab.
Click on plus sign (+) on bottom left to add a photo service.
Add the Flicker option.
Follow the login and authorization instructions.
Done! All your photos will be synchronized in you aperture library locate on ~/images/
I hope I have helped.

740: The requested operation requires elevation in java

I tried this java code, in this code i move a file from from one directory to another one,
then execute the file. I am using Windows 7 OS.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import org.apache.commons.io.FileUtils;
import org.omg.CORBA.Environment;
public class JFileChooserTest {
public static void main(String[] args) {
String filelocation="C:\\Users\\FSSD\\Desktop\\OutPut\\Target\\setup.exe";
File trgDir = new File(filelocation);
System.err
.println("file location>>>>>>>>>>>>>>>>>>>"
+ filelocation);
File desDir = new File(
"C:\\Users\\FSSD\\IndigoWorkSpace\\Swing\\test");
try {
FileUtils.copyFileToDirectory(trgDir, desDir);
// FileUtils.copyDirectory(srcDir, trgDir);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Runtime rt=Runtime.getRuntime();
try {
Process p=rt.exec("runas /user:FSSD test/setup.exe");
//Process p= rt.exec("test/setup.exe");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
While i execute this i got "740: The requested operation requires elevation " error , if any possibilities to resolve it.
Short answer is that you can't do it in-process. You need to launch a new process that is elevated at the command line. (see the elevate command).
Please see this question and answer here - they address your issue.
Service host local system network restricted 10
HKEY_LOCAL_MACHINE > SYSTEM > ControlSet001
registry value named Start in the right hand panel and double click on it.
Link

Categories

Resources