file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
Dynamic.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/elf/Dynamic.java
/******************************************************************************* * Copyright (c) 2011 - J.W. Janssen * * Copyright (c) 2000, 2008 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * J.W. Janssen - Clean up and made API more OO-oriented *******************************************************************************/ package org.flashtool.binutils.elf; import java.io.*; import java.util.*; /** * If an object file participates in dynamic linking, its program header table * will have an element of type PT_DYNAMIC. This "segment" contains the .dynamic * section. A special symbol, _DYNAMIC, labels the section, which contains an * array of the following structures. */ public class Dynamic { // CONSTANTS public final static int DYN_ENT_SIZE_32 = 8; public final static int DYN_ENT_SIZE_64 = 16; public final static int DT_NULL = 0; public final static int DT_NEEDED = 1; public final static int DT_PLTRELSZ = 2; public final static int DT_PLTGOT = 3; public final static int DT_HASH = 4; public final static int DT_STRTAB = 5; public final static int DT_SYMTAB = 6; public final static int DT_RELA = 7; public final static int DT_RELASZ = 8; public final static int DT_RELAENT = 9; public final static int DT_STRSZ = 10; public final static int DT_SYMENT = 11; public final static int DT_INIT = 12; public final static int DT_FINI = 13; public final static int DT_SONAME = 14; public final static int DT_RPATH = 15; public static final int DT_SYMBOLIC = 16; public static final int DT_REL = 17; public static final int DT_RELSZ = 18; public static final int DT_RELENT = 19; public static final int DT_PLTREL = 20; public static final int DT_DEBUG = 21; public static final int DT_TEXTREL = 22; public static final int DT_JMPREL = 23; public static final int DT_BIND_NOW = 24; public static final int DT_INIT_ARRAY = 25; public static final int DT_FINI_ARRAY = 26; public static final int DT_INIT_ARRAYSZ = 27; public static final int DT_FINI_ARRAYSZ = 28; public static final int DT_RUNPATH = 29; public static final int DT_FLAGS = 30; public static final int DT_ENCODING = 32; public static final int DT_PREINIT_ARRAY = 32; public static final int DT_PREINIT_ARRAYSZ = 33; // VARIABLES private final Section section; private long d_tag; private long d_val; private int size; private String name; // CONSTRUCTORS /** * Creates a new Dynamic instance. * * @param aSection * the section. */ private Dynamic(final Section aSection) { this.section = aSection; } // METHODS /** * Factory method. * * @param aHeader * @param aSection * @param efile * @return * @throws IOException */ static Dynamic[] create(final ElfHeader aHeader, final Section aSection, final ERandomAccessFile efile) throws IOException { if (aSection.getType() != Section.SHT_DYNAMIC) { return new Dynamic[0]; } final ArrayList<Dynamic> dynList = new ArrayList<Dynamic>(); efile.seek(aSection.getFileOffset()); int off = 0; // We must assume the section is a table ignoring the sh_entsize as it // is not set for MIPS. while (off < aSection.getSize()) { final Dynamic dynEnt = createDynamic(aHeader, aSection, efile); off += dynEnt.getSize(); if (dynEnt.getTag() != Dynamic.DT_NULL) { dynList.add(dynEnt); } } return dynList.toArray(new Dynamic[dynList.size()]); } /** * @param aClass * @param aSection * @param efile * @return * @throws IOException */ private static Dynamic createDynamic(final ElfHeader aHeader, final Section aSection, final ERandomAccessFile efile) throws IOException { final Dynamic result = new Dynamic(aSection); if (aHeader.is32bit()) { result.d_tag = efile.readIntE(); result.d_val = efile.readIntE(); result.size = DYN_ENT_SIZE_32; } else if (aHeader.is64bit()) { result.d_tag = efile.readLongE(); result.d_val = efile.readLongE(); result.size = DYN_ENT_SIZE_64; } else { throw new IOException("Unknown ELF class!"); } return result; } /** * @return */ public String getName() { return this.name; } /** * @return */ public Section getSection() { return this.section; } /** * @return */ public int getSize() { return this.size; } /** * Controls the interpretation of {@link #getValue()}. * * @return a tag, >= 0. */ public long getTag() { return this.d_tag; } /** * Returns integer values with various interpretations. * <p> * Returns either the program virtual addresses. A file's virtual addresses * might not match the memory virtual addresses during execution. When * interpreting addresses contained in the dynamic structure, the dynamic * linker computes actual addresses, based on the original file value and the * memory base address. For consistency, files do not contain relocation * entries to "correct" addresses in the dynamic structure. * * @return a virtual address. */ public long getValue() { return this.d_val; } /** * {@inheritDoc} */ @Override public String toString() { if (this.name == null) { switch ((int) this.d_tag) { case Dynamic.DT_NEEDED: case Dynamic.DT_SONAME: case Dynamic.DT_RPATH: this.name = this.section.getStringByIndex((int) this.d_val); break; default: this.name = ""; } } return this.name; } }
6,004
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
Symbol.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/elf/Symbol.java
/******************************************************************************* * Copyright (c) 2011 - J.W. Janssen * * Copyright (c) 2000, 2008 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * J.W. Janssen - Clean up and made API more OO-oriented *******************************************************************************/ package org.flashtool.binutils.elf; import java.io.*; /** * An object file's symbol table holds information needed to locate and relocate * a program's symbolic definitions and references. A symbol table index is a * subscript into this array. Index 0 both designates the first entry in the * table and serves as the undefined symbol index. */ public class Symbol implements Comparable<Object> { // CONSTANTS /* Symbol bindings */ public final static int STB_LOCAL = 0; public final static int STB_GLOBAL = 1; public final static int STB_WEAK = 2; /* Symbol type */ public final static int STT_NOTYPE = 0; public final static int STT_OBJECT = 1; public final static int STT_FUNC = 2; public final static int STT_SECTION = 3; public final static int STT_FILE = 4; /* Special Indexes */ public final static int SHN_UNDEF = 0; public final static int SHN_LORESERVE = 0xffffff00; public final static int SHN_LOPROC = 0xffffff00; public final static int SHN_HIPROC = 0xffffff1f; public final static int SHN_LOOS = 0xffffff20; public final static int SHN_HIOS = 0xffffff3f; public final static int SHN_ABS = 0xfffffff1; public final static int SHN_COMMON = 0xfffffff2; public final static int SHN_XINDEX = 0xffffffff; public final static int SHN_HIRESERVE = 0xffffffff; // VARIABLES /* NOTE: 64 bit and 32 bit ELF sections has different order */ private long st_name; private long st_value; private long st_size; private short st_info; private short st_other; private short st_shndx; private String name = null; private final Section sym_section; // CONSTRUCTORS /** * Creates a new Symbol instance. * * @param aSection */ private Symbol(final Section aSection) { this.sym_section = aSection; } // METHODS /** * @param aClass * @param aSection * @param aFile * @return * @throws IOException */ static Symbol create(ElfHeader aHeader, final Section aSection, final ERandomAccessFile aFile) throws IOException { final Symbol symbol = new Symbol(aSection); if (aHeader.is32bit()) { final byte[] addrArray = new byte[Elf.ELF32_ADDR_SIZE]; symbol.st_name = aFile.readIntE(); aFile.readFullyE(addrArray); symbol.st_value = Elf.createAddr32(addrArray); symbol.st_size = aFile.readIntE(); symbol.st_info = aFile.readByte(); symbol.st_other = aFile.readByte(); symbol.st_shndx = aFile.readShortE(); } else if (aHeader.is64bit()) { final byte[] addrArray = new byte[Elf.ELF64_ADDR_SIZE]; symbol.st_name = aFile.readIntE(); symbol.st_info = aFile.readByte(); symbol.st_other = aFile.readByte(); symbol.st_shndx = aFile.readShortE(); aFile.readFullyE(addrArray); symbol.st_value = Elf.createAddr64(addrArray); symbol.st_size = Elf.readUnsignedLong(aFile); } else { throw new IOException("Unknown ELF class!"); } return symbol; } /** * {@inheritDoc} */ @Override public int compareTo(final Object obj) { return this.st_value < ((Symbol) obj).st_value ? -1 : this.st_value == ((Symbol) obj).st_value ? 0 : 1; } /** * Returns the binding value. * * @return a binding value. */ public int getBind() { return (this.st_info >> 4) & 0xf; } /** * Returns the symbol's type and binding attributes. * * @return the raw symbol information. * @see #getBind() * @see #getType() */ public short getInfo() { return this.st_info; } /** * Returns the name of this symbol. * * @return a symbol name, never <code>null</code>. */ public String getName() { if (this.name == null) { this.name = this.sym_section.getStringByIndex((int) this.st_name); } return this.name; } /** * Returns an index into the object file's symbol string table, which holds * the character representations of the symbol names. * * @return a name index, >= 0. */ public long getNameIndex() { return this.st_name; } /** * Returns 0 and has no defined meaning. * * @return always 0. */ public short getOther() { return this.st_other; } /** * @return */ public Section getSection() { return this.sym_section; } /** * Every symbol table entry is "defined" in relation to some section; this * method returns the relevant section header table index. * * @return a section header table index, >= 0. */ public short getSectionHeaderTableIndex() { return this.st_shndx; } /** * Returns the size of this symbol. * <p> * Many symbols have associated sizes. For example, a data object's size is * the number of bytes contained in the object. This member holds 0 if the * symbol has no size or an unknown size. * </p> * * @return a symbol size. */ public long getSize() { return this.st_size; } /** * Returns the type of this symbol. * * @return a symbol type. */ public int getType() { return this.st_info & 0xf; } /** * Returns the value of the associated symbol. Depending on the context, this * may be an absolute value, an address, and so on; details appear below. * * @return a value, >= 0. */ public long getValue() { return this.st_value; } /** * {@inheritDoc} */ @Override public String toString() { return getName(); } }
6,134
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
ERandomAccessFile.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/elf/ERandomAccessFile.java
/******************************************************************************* * Copyright (c) 2011 - J.W. Janssen * * Copyright (c) 2000, 2008 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * J.W. Janssen - Clean up and made API more OO-oriented *******************************************************************************/ package org.flashtool.binutils.elf; import java.io.*; /** * @author jawi */ public final class ERandomAccessFile extends RandomAccessFile { // VARIABLES private boolean isle; // CONSTRUCTORS /** * @param aFile * @param aMode * @throws IOException */ public ERandomAccessFile(final File aFile, final String aMode) throws IOException { super(aFile, aMode); } /** * @param aFile * @param aMode * @throws IOException */ public ERandomAccessFile(final String aFile, final String aMode) throws IOException { super(aFile, aMode); } // METHODS /** * Reads <code>aBuffer.length</code> bytes from this file into the byte * array, starting at the current file pointer. * <p> * This method reads repeatedly from the file until the requested number of * bytes are read. This method blocks until the requested number of bytes are * read, the end of the stream is detected, or an exception is thrown. * </p> * <p> * <em>This method converts the read buffer according to the set endianness!</em> * </p> * * @param aBuffer * the buffer into which the data is read. * @exception EOFException * if this file reaches the end before reading all the bytes. * @exception IOException * if an I/O error occurs. */ public final void readFullyE(final byte[] aBuffer) throws IOException { super.readFully(aBuffer); byte tmp = 0; if (this.isle) { for (int i = 0; i < (aBuffer.length / 2); i++) { tmp = aBuffer[i]; aBuffer[i] = aBuffer[aBuffer.length - i - 1]; aBuffer[aBuffer.length - i - 1] = tmp; } } } /** * Reads a signed 32-bit integer from this file. * <p> * This method reads 4 bytes from the file, starting at the current file * pointer. If the bytes read, in order, are <code>b1</code>, <code>b2</code>, * <code>b3</code>, and <code>b4</code>, where * <code>0&nbsp;&lt;=&nbsp;b1, b2, b3, b4&nbsp;&lt;=&nbsp;255</code>, then the * result is equal to: <tt> * (b1 &lt;&lt; 24) | (b2 &lt;&lt; 16) + (b3 &lt;&lt; 8) + b4 * </tt>. * </p> * <p> * This method blocks until the four bytes are read, the end of the stream is * detected, or an exception is thrown. * </p> * <p> * <em>This method converts the read buffer according to the set endianness!</em> * </p> * * @return the next four bytes of this file, interpreted as an * <code>int</code>. * @exception EOFException * if this file reaches the end before reading four bytes. * @exception IOException * if an I/O error occurs. */ public final int readIntE() throws IOException { final int val[] = new int[4]; val[0] = read(); val[1] = read(); val[2] = read(); val[3] = read(); if ((val[0] | val[1] | val[2] | val[3]) < 0) { throw new EOFException(); } if (this.isle) { return ((val[3] << 24) + (val[2] << 16) + (val[1] << 8) + val[0]); } return ((val[0] << 24) + (val[1] << 16) + (val[2] << 8) + val[3]); } /** * Reads a signed 64-bit integer from this file. * <p> * This method reads eight bytes from the file, starting at the current file * pointer. If the bytes read, in order, are <code>b1</code>, <code>b2</code>, * <code>b3</code>, <code>b4</code>, <code>b5</code>, <code>b6</code>, * <code>b7</code>, and <code>b8,</code> where: <tt> * 0 &lt;= b1, b2, b3, b4, b5, b6, b7, b8 &lt;=255, * </tt> then the result is equal to: <tt> * ((long)b1 &lt;&lt; 56) + ((long)b2 &lt;&lt; 48) * + ((long)b3 &lt;&lt; 40) + ((long)b4 &lt;&lt; 32) * + ((long)b5 &lt;&lt; 24) + ((long)b6 &lt;&lt; 16) * + ((long)b7 &lt;&lt; 8) + b8 * </tt> * </p> * <p> * This method blocks until the eight bytes are read, the end of the stream is * detected, or an exception is thrown. * </p> * <p> * <em>This method converts the read buffer according to the set endianness!</em> * </p> * * @return the next eight bytes of this file, interpreted as a * <code>long</code>. * @exception EOFException * if this file reaches the end before reading eight bytes. * @exception IOException * if an I/O error occurs. */ public final long readLongE() throws IOException { final byte[] bytes = new byte[8]; long result = 0; super.readFully(bytes); int shift = 0; if (this.isle) { for (int i = 7; i >= 0; i--) { shift = i * 8; result += (((long) bytes[i]) << shift) & (0xffL << shift); } } else { for (int i = 0; i <= 7; i++) { shift = (7 - i) * 8; result += (((long) bytes[i]) << shift) & (0xffL << shift); } } return result; } /** * Reads a signed 16-bit number from this file. The method reads two * bytes from this file, starting at the current file pointer. * If the two bytes read, in order, are <code>b1</code> and <code>b2</code>, * where each of the two values is * between <code>0</code> and <code>255</code>, inclusive, then the * result is equal to: <tt> * (short)((b1 &lt;&lt; 8) | b2) * </tt></p> * <p> * This method blocks until the two bytes are read, the end of the stream is * detected, or an exception is thrown. * </p> * <p> * <em>This method converts the read buffer according to the set endianness!</em> * </p> * * @return the next two bytes of this file, interpreted as a signed 16-bit * number. * @exception EOFException * if this file reaches the end before reading two bytes. * @exception IOException * if an I/O error occurs. */ public final short readShortE() throws IOException { final int val[] = new int[2]; val[0] = read(); val[1] = read(); if ((val[0] | val[1]) < 0) { throw new EOFException(); } if (this.isle) { return (short) ((val[1] << 8) + val[0]); } return (short) ((val[0] << 8) + val[1]); } /** * Sets whether the (long) words are to be interpreted in big or little endian * mode. * * @param aLittleEndian * <code>true</code> if data is expected to be little endian, * <code>false</code> otherwise. */ public void setEndiannes(final boolean aLittleEndian) { this.isle = aLittleEndian; } }
7,166
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
ProgramHeader.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/elf/ProgramHeader.java
/******************************************************************************* * Copyright (c) 2011 - J.W. Janssen * * Copyright (c) 2000, 2008 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * J.W. Janssen - Clean up and made API more OO-oriented *******************************************************************************/ package org.flashtool.binutils.elf; import java.io.*; /** * An executable or shared object file's program header table is an array of * structures, each describing a segment or other information the system needs * to prepare the program for execution. An object file segment contains one or * more sections. Program headers are meaningful only for executable and shared * object files. */ public class ProgramHeader { // CONSTANTS public static final int PT_NULL = 0; public static final int PT_LOAD = 1; public static final int PT_DYNAMIC = 2; public static final int PT_INTERP = 3; public static final int PT_NOTE = 4; public static final int PT_SHLIB = 5; public static final int PT_PHDR = 6; public static final int PT_GNU_EH_FRAME = 0x6474e550; public static final int PT_GNU_STACK = 0x6474e551; public static final int PT_GNU_RELRO = 0x6474e552; public static final int PT_PAX_FLAGS = 0x65041580; public static final int PT_SUNWBSS = 0x6ffffffa; public static final int PT_SUNWSTACK = 0x6ffffffb; public static final int PT_ARM_ARCHEXT = 0x70000000; public static final int PT_ARM_UNWIND = 0x70000001; public static final int PF_X = (1 << 0); /* Segment is executable */ public static final int PF_W = (1 << 1); /* Segment is writable */ public static final int PF_R = (1 << 2); /* Segment is readable */ public static final int PF_PAGEEXEC = (1 << 4); /* Enable PAGEEXEC */ public static final int PF_NOPAGEEXEC = (1 << 5); /* Disable PAGEEXEC */ public static final int PF_SEGMEXEC = (1 << 6); /* Enable SEGMEXEC */ public static final int PF_NOSEGMEXEC = (1 << 7); /* Disable SEGMEXEC */ public static final int PF_MPROTECT = (1 << 8); /* Enable MPROTECT */ public static final int PF_NOMPROTECT = (1 << 9); /* Disable MPROTECT */ public static final int PF_RANDEXEC = (1 << 10); /* Enable RANDEXEC */ public static final int PF_NORANDEXEC = (1 << 11); /* Disable RANDEXEC */ public static final int PF_EMUTRAMP = (1 << 12); /* Enable EMUTRAMP */ public static final int PF_NOEMUTRAMP = (1 << 13); /* Disable EMUTRAMP */ public static final int PF_RANDMMAP = (1 << 14); /* Enable RANDMMAP */ public static final int PF_NORANDMMAP = (1 << 15); /* Disable RANDMMAP */ public static final int PF_MASKOS = 0x0ff00000; /* OS-specific */ public static final int PF_MASKPROC = 0xf0000000; /* Processor-specific */ /* NOTE: 64 bit and 32 bit ELF have different order and size of elements */ private int p_type; private long p_offset; private long p_vaddr; private long p_paddr; private long p_filesz; private long p_memsz; private int p_flags; private long p_align; // CONSTRUCTORS /** * Creates a new PHdr instance. */ public ProgramHeader() { super(); } // METHODS /** * @param aHeader * @param aFile * @return */ static ProgramHeader[] createHeaders(ElfHeader aHeader, ERandomAccessFile aFile) throws IOException { if (!aHeader.hasProgramHeaderTable()) { return new ProgramHeader[0]; } final int length = aHeader.getProgramHeaderEntryCount(); final int phentsize = aHeader.getProgramHeaderEntrySize(); final ProgramHeader phdrs[] = new ProgramHeader[length]; long offset = aHeader.getProgramHeaderFileOffset(); for (int i = 0; i < length; i++, offset += phentsize) { aFile.seek(offset); phdrs[i] = createHeader(aHeader, aFile); } return phdrs; } /** * @param aHeader * @param aFile * @return * @throws IOException */ private static ProgramHeader createHeader(ElfHeader aHeader, ERandomAccessFile aFile) throws IOException { ProgramHeader result = new ProgramHeader(); if (aHeader.is32bit()) { final byte[] addrArray = new byte[Elf.ELF32_ADDR_SIZE]; result.p_type = aFile.readIntE(); result.p_offset = aFile.readIntE(); aFile.readFullyE(addrArray); result.p_vaddr = Elf.createAddr32(addrArray); aFile.readFullyE(addrArray); result.p_paddr = Elf.createAddr32(addrArray); result.p_filesz = aFile.readIntE(); result.p_memsz = aFile.readIntE(); result.p_flags = aFile.readIntE(); result.p_align = aFile.readIntE(); } else if (aHeader.is64bit()) { final byte[] addrArray = new byte[Elf.ELF64_ADDR_SIZE]; result.p_type = aFile.readIntE(); result.p_flags = aFile.readIntE(); result.p_offset = Elf.readUnsignedLong(aFile); aFile.readFullyE(addrArray); result.p_vaddr = Elf.createAddr64(addrArray); aFile.readFullyE(addrArray); result.p_paddr = Elf.createAddr64(addrArray); result.p_filesz = Elf.readUnsignedLong(aFile); result.p_memsz = Elf.readUnsignedLong(aFile); result.p_align = Elf.readUnsignedLong(aFile); } else { throw new IOException("Unknown ELF class!"); } return result; } /** * Loadable process segments must have congruent values for p_vaddr and * p_offset, modulo the page size. This member gives the value to which the * segments are aligned in memory and in the file. Values 0 and 1 mean that no * alignment is required. Otherwise, p_align should be a positive, integral * power of 2, and p_addr should equal p_offset, modulo p_align. * * @return the alignment */ public long getAlignment() { return this.p_align; } /** * Returns the offset from the beginning of the file at which the first byte * of the segment resides. * * @return the file offset (in bytes), >= 0. */ public long getFileOffset() { return this.p_offset; } /** * Returns the number of bytes in the file image of the segment; it may be * zero. * * @return the file segment size, >= 0. */ public long getFileSize() { return this.p_filesz; } /** * Returns the flags relevant to the segment. * * @return the flags. */ public long getFlags() { return this.p_flags; } /** * Returns the number of bytes in the memory image of the segment; it may be * zero. * * @return the memory size of this segment, >= 0. */ public long getMemorySize() { return this.p_memsz; } /** * On systems for which physical addressing is relevant, this member is * reserved for the segment's physical address. This member requires operating * system specific information. * * @return the p_paddr */ public long getPhysicalAddress() { return this.p_paddr; } /** * Returns what kind of segment this array element describes or how to * interpret the array element's information. * * @return the type of this header. */ public long getType() { return this.p_type; } /** * Returns a string name for the type of this program header. * * @return a type name, never <code>null</code>. */ public String getTypeName() { switch ((int) getType()) { case PT_NULL: return "PT_NULL (Unused)"; case PT_LOAD: return "PT_LOAD (Loadable segment)"; case PT_DYNAMIC: return "PT_DYNAMIC (Dynamic linking information)"; case PT_INTERP: return "PT_INTERP (Interpreter path)"; case PT_NOTE: return "PT_NOTE (Location, size and auxiliary information)"; case PT_SHLIB: return "PT_SHLIB (Reserved)"; case PT_PHDR: return "PT_PHDR (Location and size of program header)"; case PT_GNU_EH_FRAME: return "PT_GNU_EH_FRAME (GNU: EH frame)"; case PT_GNU_STACK: return "PT_GNU_STACK (GNU: Indicates stack executability)"; case PT_GNU_RELRO: return "PT_GNU_RELRO (GNU: Read-only after relocation)"; case PT_PAX_FLAGS: return "PT_PAX_FLAGS (PaX: Indicates PaX flag markings)"; case PT_SUNWBSS: return "PT_SUNWBSS (Sun: Sun Specific segment)"; case PT_SUNWSTACK: return "PT_SUNWSTACK (Sun: Stack segment)"; case PT_ARM_ARCHEXT: return "PT_ARM_ARCHEXT (ARM: Platform architecture compatibility information)"; case PT_ARM_UNWIND: return "PT_ARM_UNWIND (ARM: Exception unwind tables)"; default: return String.format("Unknown/processor specific (0x%x)", getType()); } } /** * Returns the virtual address at which the first byte of the segment resides * in memory. * * @return the virtual address, >= 0. */ public long getVirtualAddress() { return this.p_vaddr; } }
9,146
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
Elf.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/elf/Elf.java
/******************************************************************************* * Copyright (c) 2011 - J.W. Janssen * * Copyright (c) 2000, 2008 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * Markus Schorn (Wind River Systems) * J.W. Janssen - Clean up and made API more OO-oriented *******************************************************************************/ package org.flashtool.binutils.elf; import java.io.*; import java.math.*; import java.util.*; /** * Denotes an ELF (Executable and Linking Format) file. * <p> * There are three main types of object files: * </p> * <ul> * <li>A relocatable file holds code and data suitable for linking with other * object files to create an executable or a shared object file;</li> * <li>An executable file holds a program suitable for execution;</li> * <li>A shared object file holds code and data suitable for linking in two * contexts. First, the link editor may process it with other relocatable and * shared object files to create another object file. Second, the dynamic linker * combines it with an executable file and other shared objects to create a * process image.</li> * </ul> * <p> * Created by the assembler and link editor, object files are binary * representations of programs intended to execute directly on a processor. * Programs that require other abstract machines are excluded. * </p> */ public class Elf { // CONSTANTS public final static int ELF32_ADDR_SIZE = 4; public final static int ELF32_OFF_SIZE = 4; public final static int ELF64_ADDR_SIZE = 8; public final static int ELF64_OFF_SIZE = 8; // VARIABLES private ERandomAccessFile efile; private ElfHeader ehdr; private Section[] sections; private String file; private byte[] section_strtab; private int syms = 0; private Symbol[] symbols; private Symbol[] symtab_symbols; private Section symtab_sym; private Symbol[] dynsym_symbols; private Section dynsym_sym; // CONSTRUCTORS /** * @param aFile * @throws IOException */ public Elf( final File aFile ) throws IOException { try { this.efile = new ERandomAccessFile( aFile, "r" ); this.ehdr = new ElfHeader( this.efile ); this.file = aFile.getAbsolutePath(); } finally { if ( this.ehdr == null ) { dispose(); } } } /** * A hollow entry, to be used with caution in controlled situations */ private Elf() { } // METHODS /** * @param array * @return * @throws IOException */ public static Attribute getAttributes( final byte[] array ) throws IOException { final Elf emptyElf = new Elf(); emptyElf.ehdr = new ElfHeader( array ); emptyElf.sections = new Section[0]; final Attribute attrib = emptyElf.getAttributes(); emptyElf.dispose(); return attrib; } /** * @param file * @return * @throws IOException */ public static Attribute getAttributes( final File file ) throws IOException { final Elf elf = new Elf( file ); final Attribute attrib = elf.getAttributes(); elf.dispose(); return attrib; } /** * @param aBytes * @return */ static long createAddr32( final byte[] aBytes ) { final long result = new BigInteger( 1, aBytes ).longValue(); return result & 0xFFFFFFFF; } /** * @param aBytes * @return */ static long createAddr64( final byte[] aBytes ) { return new BigInteger( 1, aBytes ).longValue(); } /** * @param file * @return * @throws IOException */ static long readUnsignedLong( final ERandomAccessFile file ) throws IOException { final long result = file.readLongE(); if ( result < 0 ) { throw new IOException( "Maximal file offset is " + Long.toHexString( Long.MAX_VALUE ) + " given offset is " + Long.toHexString( result ) ); } return result; } /** * Disposes this ELF object and closes all associated resources. */ public void dispose() { try { if ( this.efile != null ) { this.efile.close(); this.efile = null; } } catch ( IOException exception ) { // Ignore XXX } } /** * @return * @throws IOException */ public Attribute getAttributes() throws IOException { return Attribute.create( this.ehdr, getSections() ); } /** * @param section * @return * @throws IOException */ public Dynamic[] getDynamicSections( final Section section ) throws IOException { return Dynamic.create( this.ehdr, section, this.efile ); } /** * @return */ public Symbol[] getDynamicSymbols() { if ( this.dynsym_symbols == null ) { throw new IllegalStateException( "Dynamic symbols not yet loaded!" ); } return this.dynsym_symbols; } /** * @return */ public String getFilename() { return this.file; } /** * @return * @throws IOException */ public ElfHeader getHeader() throws IOException { return this.ehdr; } /** * @return * @throws IOException */ public ProgramHeader[] getProgramHeaders() throws IOException { return ProgramHeader.createHeaders( this.ehdr, this.efile ); } /** * @param name * @return * @throws IOException */ public Section getSectionByName( final String name ) throws IOException { final Section[] secs = getSections(); for ( Section section : secs ) { if ( name.equals( section.getName() ) ) { return section; } } return null; } /** * @return * @throws IOException */ public Section[] getSections() throws IOException { if ( this.sections == null ) { this.sections = Section.create( this, this.ehdr, this.efile ); for ( int i = 0; i < this.sections.length; i++ ) { if ( this.sections[i].getType() == Section.SHT_SYMTAB ) { this.syms = i; } if ( ( this.syms == 0 ) && ( this.sections[i].getType() == Section.SHT_DYNSYM ) ) { this.syms = i; } } } return this.sections; } /** * @param type * @return * @throws IOException */ public Section[] getSections( final int type ) throws IOException { final ArrayList<Section> result = new ArrayList<Section>(); final Section[] secs = getSections(); for ( Section section : secs ) { if ( type == section.getType() ) { result.add( section ); } } return result.toArray( new Section[result.size()] ); } /** * This section describes the default string table. String table sections hold * null-terminated character sequences, commonly called strings. The object * file uses these strings to represent symbol and section names. * * @return the raw string table, never <code>null</code>. * @throws IOException * in case of I/O problems. */ public byte[] getStringTable() throws IOException { if ( this.section_strtab == null ) { final int shstrndx = this.ehdr.getStringTableSectionIndex(); if ( ( shstrndx > this.sections.length ) || ( shstrndx < 0 ) ) { this.section_strtab = new byte[0]; } final int size = ( int )this.sections[shstrndx].getSize(); if ( ( size <= 0 ) || ( size > this.efile.length() ) ) { this.section_strtab = new byte[0]; } this.section_strtab = new byte[size]; this.efile.seek( this.sections[shstrndx].getFileOffset() ); this.efile.read( this.section_strtab ); } return this.section_strtab; } /** * /* return the address of the function that address is in * * @param vma * @return */ public Symbol getSymbol( final long vma ) { if ( this.symbols == null ) { return null; } // @@@ If this works, move it to a single instance in this class. final SymbolComparator symbol_comparator = new SymbolComparator(); int ndx = Arrays.binarySearch( this.symbols, vma, symbol_comparator ); if ( ndx > 0 ) { return this.symbols[ndx]; } if ( ndx == -1 ) { return null; } ndx = -ndx - 1; return this.symbols[ndx - 1]; } /** * @return */ public Symbol[] getSymbols() { return this.symbols; } /** * @return */ public Symbol[] getSymtabSymbols() { return this.symtab_symbols; } /** * Loads the symbol tables. * * @throws IOException * in case of I/O problems. */ public void loadSymbols() throws IOException { if ( this.symbols == null ) { Section section[] = getSections( Section.SHT_SYMTAB ); this.symtab_sym = null; if ( section.length > 0 ) { this.symtab_sym = section[0]; } this.symtab_symbols = loadSymbolsBySection( this.symtab_sym ); section = getSections( Section.SHT_DYNSYM ); this.dynsym_sym = null; if ( section.length > 0 ) { this.dynsym_sym = section[0]; } this.dynsym_symbols = loadSymbolsBySection( this.dynsym_sym ); if ( this.symtab_sym != null ) { // sym = symtab_sym; this.symbols = this.symtab_symbols; } else if ( this.dynsym_sym != null ) { // sym = dynsym_sym; this.symbols = this.dynsym_symbols; } } } /** * Reads the program segment from the ELF file and writes it to the given * writer. * * @param aHeader * the program segment to read; * @param aWriter * the writer to write the read data to. * @throws IOException * in case of I/O problems. */ public void readSegment( ProgramHeader aHeader, OutputStream aWriter ) throws IOException { this.efile.seek( aHeader.getFileOffset() ); this.efile.setEndiannes( this.ehdr.isLittleEndian() ); long size = aHeader.getFileSize(); if ( this.ehdr.is32bit() ) { size /= 4; } else if ( this.ehdr.is64bit() ) { size /= 8; } while ( size-- >= 0 ) { if ( this.ehdr.is32bit() ) { byte[] buf = new byte[4]; this.efile.readFullyE( buf ); aWriter.write( buf, 0, 4 ); } else { byte[] buf = new byte[8]; this.efile.readFullyE( buf ); aWriter.write( buf, 0, 8 ); } } } /** * @param section * @param index * @return * @throws IOException */ final String getStringFromSection( final Section section, final int index ) throws IOException { if ( index > section.getSize() ) { return ""; } final StringBuffer str = new StringBuffer(); // Most string symbols will be less than 50 bytes in size final byte[] tmp = new byte[50]; this.efile.seek( section.getFileOffset() + index ); while ( true ) { int len = this.efile.read( tmp ); for ( int i = 0; i < len; i++ ) { if ( tmp[i] == 0 ) { len = 0; break; } str.append( ( char )tmp[i] ); } if ( len <= 0 ) { break; } } return str.toString(); } /** * Make sure we do not leak the fds. */ @Override protected void finalize() throws Throwable { try { dispose(); } finally { super.finalize(); } } /** * @param aSection * @return * @throws IOException */ private Symbol[] loadSymbolsBySection( final Section aSection ) throws IOException { if ( aSection == null ) { return new Symbol[0]; } return aSection.loadSymbols( this.ehdr, this.efile ); } }
12,004
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
Coff.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/coff/Coff.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * Copyright (c) 2000, 2010 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.coff; import java.io.*; import org.flashtool.binutils.elf.ERandomAccessFile; import org.flashtool.binutils.elf.*; /** * */ public class Coff { // VARIABLES private FileHeader filehdr; private OptionalHeader opthdr; private final ERandomAccessFile rfile; private byte[] string_table; private SectionHeader[] scnhdrs; private Symbol[] symbols; // CONSTRUCTORS /** * Creates a new Coff instance. * * @param aFile * @throws IOException */ public Coff(File aFile) throws IOException { this.rfile = new ERandomAccessFile(aFile, "r"); this.rfile.setEndiannes(true /* aLittleEndian */); try { this.filehdr = new FileHeader(this.rfile); if (this.filehdr.hasOptionalHeader()) { this.opthdr = new OptionalHeader(this.rfile); } } finally { if (this.filehdr == null) { this.rfile.close(); } } } // METHODS /** * @return * @throws IOException */ public FileHeader getFileHeader() throws IOException { return this.filehdr; } /** * @return * @throws IOException */ public OptionalHeader getOptionalHeader() throws IOException { return this.opthdr; } /** * @return * @throws IOException */ public SectionHeader[] getSectionHeaders() throws IOException { if (this.scnhdrs == null) { FileHeader header = getFileHeader(); this.scnhdrs = new SectionHeader[header.getSymbolTableEntryCount()]; for (int i = 0; i < this.scnhdrs.length; i++) { this.scnhdrs[i] = new SectionHeader(this.rfile); } } return this.scnhdrs; } /** * @return * @throws IOException */ public byte[] getStringTable() throws IOException { if (this.string_table == null) { FileHeader header = getFileHeader(); long symbolSize = Symbol.SYMSZ * header.getSymbolTableEntryCount(); long offset = header.getSymbolTableOffset() + symbolSize; this.rfile.seek(offset); int str_len = this.rfile.readIntE(); if ((str_len > 4) && (str_len < this.rfile.length())) { str_len -= 4; this.string_table = new byte[str_len]; this.rfile.seek(offset + 4); this.rfile.readFully(this.string_table); } else { this.string_table = new byte[0]; } } return this.string_table; } /** * @return * @throws IOException */ public Symbol[] getSymbols() throws IOException { if (this.symbols == null) { long offset = getFileHeader().getSymbolTableOffset(); this.rfile.seek(offset); this.symbols = new Symbol[getFileHeader().getSymbolTableEntryCount()]; for (int i = 0; i < this.symbols.length; i++) { this.symbols[i] = new Symbol(this.rfile); } } return this.symbols; } /** * {@inheritDoc} */ @Override public String toString() { StringBuffer buffer = new StringBuffer(); try { FileHeader header = getFileHeader(); if (header != null) { buffer.append(header); } } catch (IOException e) { e.printStackTrace(); } try { OptionalHeader opt = null; opt = getOptionalHeader(); if (opt != null) { buffer.append(opt); } } catch (IOException e) { e.printStackTrace(); } try { SectionHeader[] sections = getSectionHeaders(); for (SectionHeader section : sections) { buffer.append(section); } } catch (IOException e) { } try { Symbol[] table = getSymbols(); for (Symbol element : table) { buffer.append(element.getName(getStringTable())).append('\n'); } } catch (IOException e) { } // try { // String[] strings = getStringTable(getStringTable()); // for (int i = 0; i < strings.length; i++) { // buffer.append(strings[i]); // } // } catch (IOException e) { // e.printStackTrace(); // } return buffer.toString(); } }
4,752
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
Reloc.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/coff/Reloc.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * Copyright (c) 2000, 2010 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.coff; import java.io.*; import org.flashtool.binutils.elf.ERandomAccessFile; import org.flashtool.binutils.elf.*; /** * */ public class Reloc { // VARIABLES /** * 4 byte: Pointer to an area in raw data that represents a referenced * address. */ private final int r_vaddr; /** 4 byte: Index into symbol table. */ private final int r_symndx; /** 2 byte(unsigned short): Type of address reference. */ private final int r_type; // CONSTRUCTORS /** * Creates a new Reloc instance. * * @param aFile * @throws IOException */ Reloc(ERandomAccessFile aFile) throws IOException { this.r_vaddr = aFile.readIntE(); this.r_symndx = aFile.readIntE(); this.r_type = aFile.readShortE(); } // METHODS /** * Returns a pointer to an area in raw data that represents a referenced * address. * * @return */ public int getAddress() { return this.r_vaddr; } /** * Returns the index into symbol table. * * @return a symbol table index, >= 0. */ public int getSymbolTableIndex() { return this.r_symndx; } /** * Returns the address reference type. * * @return an address reference type, >= 0. */ public int getType() { return this.r_type; } /** * {@inheritDoc} */ @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("RELOC VALUES").append('\n'); buffer.append("r_vaddr = ").append(this.r_vaddr); buffer.append(" r_symndx = ").append(this.r_symndx).append('\n'); return buffer.toString(); } }
2,284
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
OptionalHeader.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/coff/OptionalHeader.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * Copyright (c) 2000, 2010 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.coff; import java.io.*; import org.flashtool.binutils.elf.ERandomAccessFile; import org.flashtool.binutils.elf.*; /** * */ public class OptionalHeader { // CONSTANTS public final static int AOUTHDRSZ = 28; // VARIABLES private final short magic; /* 2 bytes: type of file */ private final short vstamp; /* 2 bytes: version stamp */ private final int tsize; /* 4 bytes: text size in bytes, padded to FW bdry */ private final int dsize; /* 4 bytes: initialized data " " */ private final int bsize; /* 4 bytes: uninitialized data " " */ private final int entry; /* 4 bytes: entry pt. */ private final int text_start; /* 4 bytes: base of text used for this file */ private final int data_start; /* 4 bytes: base of data used for this file */ // CONSTRUCTORS /** * Creates a new OptionalHeader instance. * * @param aFile * @throws IOException */ OptionalHeader(ERandomAccessFile aFile) throws IOException { aFile.seek(aFile.getFilePointer() + FileHeader.FILHSZ); this.magic = aFile.readShortE(); this.vstamp = aFile.readShortE(); this.tsize = aFile.readIntE(); this.dsize = aFile.readIntE(); this.bsize = aFile.readIntE(); this.entry = aFile.readIntE(); this.text_start = aFile.readIntE(); this.data_start = aFile.readIntE(); } // METHODS /** * Returns the size of uninitialised data. * * @return the uninitialised data size, >= 0. */ public int getBSize() { return this.bsize; } /** * Returns the current value of data_start. * * @return the data_start */ public int getDataStart() { return this.data_start; } /** * Returns the size of initialised data. * * @return the initialised data size, >= 0. */ public int getDSize() { return this.dsize; } /** * Returns the current value of entry. * * @return the entry */ public int getEntryPoint() { return this.entry; } /** * Returns the current value of magic. * * @return the magic */ public short getMagic() { return this.magic; } /** * Returns the current value of tsize. * * @return the tsize */ public int getTextSize() { return this.tsize; } /** * Returns the current value of text_start. * * @return the text_start */ public int getTextStart() { return this.text_start; } /** * Returns the current value of vstamp. * * @return the vstamp */ public short getVersionStamp() { return this.vstamp; } /** * {@inheritDoc} */ @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("OPTIONAL HEADER VALUES").append('\n'); buffer.append("magic = ").append(this.magic).append('\n'); buffer.append("vstamp = ").append(this.vstamp).append('\n'); buffer.append("tsize = ").append(this.tsize).append('\n'); buffer.append("dsize = ").append(this.dsize).append('\n'); buffer.append("bsize = ").append(this.bsize).append('\n'); buffer.append("entry = ").append(this.entry).append('\n'); buffer.append("text_start = ").append(this.text_start).append('\n'); buffer.append("data_start = ").append(this.data_start).append('\n'); return buffer.toString(); } }
4,009
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
SectionHeader.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/coff/SectionHeader.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * Copyright (c) 2000, 2010 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.coff; import java.io.*; import org.flashtool.binutils.elf.ERandomAccessFile; import org.flashtool.binutils.elf.*; /** * */ public class SectionHeader { // CONSTANTS /* names of "special" sections */ public final static String _TEXT = ".text"; public final static String _DATA = ".data"; public final static String _BSS = ".bss"; public final static String _COMMENT = ".comment"; public final static String _LIB = ".lib"; /* s_flags "type". */ /** "regular": allocated, relocated, loaded */ public final static int STYP_REG = 0x0000; /** "dummy": relocated only */ public final static int STYP_DSECT = 0x0001; /** "noload": allocated, relocated, not loaded */ public final static int STYP_NOLOAD = 0x0002; /** "grouped": formed of input sections */ public final static int STYP_GROUP = 0x0004; /** "padding": not allocated, not relocated, loaded */ public final static int STYP_PAD = 0x0008; /** * "copy": for decision function used by field update; not allocated, not * relocated, loaded; reloc & lineno entries processed normally */ public final static int STYP_COPY = 0x0010; /** section contains text only. */ public final static int STYP_TEXT = 0x0020; /** * In 3b Update files (output of ogen), sections which appear in SHARED * segments of the Pfile will have the S_SHRSEG flag set by ogen, to inform * dufr that updating 1 copy of the proc. will update all process invocations. */ public final static int S_SHRSEG = 0x0020; /** section contains data only */ public final static int STYP_DATA = 0x0040; /** section contains bss only */ public final static int STYP_BSS = 0x0080; /** * In a minimal file or an update file, a new function (as compared with a * replaced function) */ public final static int S_NEWFCN = 0x0100; /** comment: not allocated not relocated, not loaded */ public final static int STYP_INFO = 0x0200; /** overlay: relocated not allocated or loaded */ public final static int STYP_OVER = 0x0400; /** for .lib: same as INFO */ public final static int STYP_LIB = 0x0800; /** merge section -- combines with text, data or bss sections only */ public final static int STYP_MERGE = 0x2000; /** * section will be padded with no-op instructions wherever padding is * necessary and there is a word of contiguous bytes beginning on a word * boundary. */ public final static int STYP_REVERSE_PAD = 0x4000; /** Literal data (like STYP_TEXT) */ public final static int STYP_LIT = 0x8020; // VARIABLES private final byte[] s_name = new byte[8]; // 8 bytes: section name private final int s_paddr; // 4 bytes: physical address, aliased s_nlib private final int s_vaddr; // 4 bytes: virtual address private final int s_size; // 4 bytes: section size private final int s_scnptr; // 4 bytes: file ptr to raw data for section private final int s_relptr; // 4 bytes: file ptr to relocation private final int s_lnnoptr; // 4 bytes: file ptr to line numbers private final int s_nreloc; // 2 bytes: number of relocation entries private final int s_nlnno; // 2 bytes: number of line number entries private final int s_flags; // 4 bytes: flags private final ERandomAccessFile sfile; // CONSTRUCTORS /** * Creates a new SectionHeader instance. * * @param aFile * @param offset * @throws IOException */ SectionHeader(ERandomAccessFile aFile) throws IOException { this.sfile = aFile; aFile.readFully(this.s_name); this.s_paddr = aFile.readIntE(); this.s_vaddr = aFile.readIntE(); this.s_size = aFile.readIntE(); this.s_scnptr = aFile.readIntE(); this.s_relptr = aFile.readIntE(); this.s_lnnoptr = aFile.readIntE(); this.s_nreloc = aFile.readShortE(); this.s_nlnno = aFile.readShortE(); this.s_flags = aFile.readIntE(); } /** * Returns the current value of s_flags. * * @return the s_flags */ public int getFlags() { return this.s_flags; } /** * @return * @throws IOException */ public LineNo[] getLineNumbers() throws IOException { LineNo[] lines = new LineNo[this.s_nlnno]; this.sfile.seek(this.s_lnnoptr); for (int i = 0; i < this.s_nlnno; i++) { lines[i] = new LineNo(this.sfile); } return lines; } /** * @return */ public int getPhysicalAddress() { return this.s_paddr; } /** * @return * @throws IOException */ public byte[] getRawData() throws IOException { byte[] data = new byte[this.s_size]; this.sfile.seek(this.s_scnptr); this.sfile.readFully(data); return data; } /** * @return * @throws IOException */ public Reloc[] getRelocs() throws IOException { Reloc[] relocs = new Reloc[this.s_nreloc]; this.sfile.seek(this.s_relptr); for (int i = 0; i < this.s_nreloc; i++) { relocs[i] = new Reloc(this.sfile); } return relocs; } /** * @return */ public int getSize() { return this.s_size; } /** * @return */ public int getVirtualAddress() { return this.s_vaddr; } /** * {@inheritDoc} */ @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("SECTION HEADER VALUES").append('\n'); buffer.append(new String(this.s_name)).append('\n'); buffer.append("s_paddr = ").append(this.s_paddr).append('\n'); buffer.append("s_vaddr = ").append(this.s_vaddr).append('\n'); buffer.append("s_size = ").append(this.s_size).append('\n'); buffer.append("s_scnptr = ").append(this.s_scnptr).append('\n'); buffer.append("s_relptr = ").append(this.s_relptr).append('\n'); buffer.append("s_lnnoptr = ").append(this.s_lnnoptr).append('\n'); buffer.append("s_nreloc = ").append(this.s_nreloc).append('\n'); buffer.append("s_nlnno = ").append(this.s_nlnno).append('\n'); buffer.append("s_flags = ").append(this.s_flags).append('\n'); // /* try { Reloc[] rcs = getRelocs(); for (Reloc rc : rcs) { buffer.append(rc); } } catch (IOException e) { } try { LineNo[] nos = getLineNumbers(); for (LineNo no : nos) { buffer.append(no); } } catch (IOException e) { } // */ return buffer.toString(); } }
7,028
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
LineNo.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/coff/LineNo.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * Copyright (c) 2000, 2010 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.coff; import java.io.*; import org.flashtool.binutils.elf.ERandomAccessFile; import org.flashtool.binutils.elf.*; /** * */ public class LineNo { // VARIABLES /** * long. Index into symbol table if l_linn0 == 0. * Break-pointable address if l_lnno > 0. */ private final int l_addr; /** unsigned short. Line number */ private final int l_lnno; // CONSTRUCTORS /** * Creates a new LineNo instance. * * @param aFile * @throws IOException */ LineNo(ERandomAccessFile aFile) throws IOException { this.l_addr = aFile.readIntE(); this.l_lnno = aFile.readShortE(); } // METHODS /** * Returns the function address. * * @return the address, >= 0. */ public int getAddress() { return this.l_addr; } /** * Returns the line number. * * @return the line number, >= 0. */ public int getLineNumber() { return this.l_lnno; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); if (this.l_lnno == 0) { buffer.append("Function address = ").append(this.l_addr).append('\n'); } else { buffer.append("line #").append(this.l_lnno); buffer.append(" at address = ").append(this.l_addr).append('\n'); } return buffer.toString(); } }
2,028
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
FileHeader.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/coff/FileHeader.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * Copyright (c) 2000, 2010 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.coff; import java.io.*; import java.text.*; import java.util.*; import org.flashtool.binutils.elf.ERandomAccessFile; import org.flashtool.binutils.elf.*; /** * */ public class FileHeader { // CONSTANTS public final static int FILHSZ = 20; // relocation info stripped from file public final static int F_RELFLG = 0x0001; // file is executable (no unresolved external references) public final static int F_EXEC = 0x0002; // line numbers stripped from file public final static int F_LNNO = 0x0004; // local symbols stripped from file public final static int F_LSYMS = 0x0008; // file is 16-bit little-endian public final static int F_AR16WR = 0x0080; // file is 32-bit little-endian public final static int F_AR32WR = 0x0100; // file is 32-bit big-endian public final static int F_AR32W = 0x0200; // rs/6000 aix: dynamically loadable w/imports & exports public final static int F_DYNLOAD = 0x1000; // rs/6000 aix: file is a shared object public final static int F_SHROBJ = 0x2000; // PE format DLL. public final static int F_DLL = 0x2000; // VARIABLES private final int magic; /* 00-01 2 bytes: magic number */ private final int nscns; /* 02-03 2 bytes: number of sections: 2 bytes */ private final int timdat; /* 04-07 4 bytes: time & date stamp */ private final int symptr; /* 08-11 4 bytes: file pointer to symtab */ private final int nsyms; /* 12-15 4 bytes: number of symtab entries */ private final int opthdr; /* 16-17 2 bytes: sizeof(optional hdr) */ private final int flags; /* 18-19 2 bytes: flags */ // CONSTRUCTORS /** * Creates a new FileHeader instance. * * @param aFile * @throws IOException */ FileHeader(ERandomAccessFile aFile) throws IOException { this.magic = aFile.readShortE(); this.nscns = aFile.readShortE(); this.timdat = aFile.readIntE(); this.symptr = aFile.readIntE(); this.nsyms = aFile.readIntE(); this.opthdr = aFile.readShortE(); this.flags = aFile.readShortE(); } // METHODS /** * Returns the time & date stamp. * * @return a time & date stamp. */ public int getDateTime() { return this.timdat; } /** * Returns the current value of flags. * * @return the flags */ public int getFlags() { return this.flags; } /** * Returns the current value of magic. * * @return the magic */ public int getMagic() { return this.magic; } /** * @return */ public int getOptionalHeaderSize() { return this.opthdr; } /** * Returns the number of sections. * * @return a section count, >= 0. */ public int getSectionCount() { return this.nscns; } /** * @return the file pointer to symbol table. */ public int getSymbolTableEntryCount() { return this.nsyms; } /** * @return the file pointer to symbol table. */ public int getSymbolTableOffset() { return this.symptr; } /** * @return */ public boolean hasOptionalHeader() { return this.opthdr > 0; } /** * @return */ public boolean isDebug() { return !((this.flags & F_LNNO) == F_LNNO); } /** * @return */ public boolean isExec() { return (this.flags & F_EXEC) == F_EXEC; } /** * @return */ public boolean isStrip() { return (this.flags & F_RELFLG) == F_RELFLG; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("FILE HEADER VALUES").append('\n'); buffer.append("f_magic = ").append(this.magic).append('\n'); buffer.append("f_nscns = ").append(this.nscns).append('\n'); buffer.append("f_timdat = "); buffer.append(DateFormat.getDateInstance().format(new Date(this.timdat))); buffer.append('\n'); buffer.append("f_symptr = ").append(this.symptr).append('\n'); buffer.append("f_nsyms = ").append(this.nsyms).append('\n'); buffer.append("f_opthdr = ").append(this.opthdr).append('\n'); buffer.append("f_flags = ").append(this.flags).append('\n'); return buffer.toString(); } }
4,820
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
Symbol.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/coff/Symbol.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * Copyright (c) 2000, 2010 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.coff; import java.io.*; public class Symbol { // CONSTANTS public final static int SYMSZ = 18; public final static int SYMNMLEN = 8; /* Derived types, in n_type. */ /** no derived type */ public final static int DT_NON = 0; /** pointer */ public final static int DT_PTR = 1; /** function */ public final static int DT_FCN = 2; /** array */ public final static int DT_ARY = 3; public final static int N_TMASK = 0x30; public final static int N_BTSHFT = 4; public final static int N_TSHIFT = 2; /** No symbol */ public final static int T_NULL = 0x00; /** -- 0001 void function argument (not used) */ public final static int T_VOID = 0x01; /** -- 0010 character */ public final static int T_CHAR = 0x02; /** -- 0011 short integer */ public final static int T_SHORT = 0x03; /** -- 0100 integer */ public final static int T_INT = 0x04; /** -- 0101 long integer */ public final static int T_LONG = 0x05; /** -- 0110 floating point */ public final static int T_FLOAT = 0x06; /** -- 0111 double precision float */ public final static int T_DOUBLE = 0x07; /** -- 1000 structure */ public final static int T_STRUCT = 0x08; /** -- 1001 union */ public final static int T_UNION = 0x09; /** -- 1010 enumeration */ public final static int T_ENUM = 0x10; /** -- 1011 member of enumeration */ public final static int T_MOE = 0x11; /** -- 1100 unsigned character */ public final static int T_UCHAR = 0x12; /** -- 1101 unsigned short */ public final static int T_USHORT = 0x13; /** -- 1110 unsigned integer */ public final static int T_UINT = 0x14; /** -- 1111 unsigned long */ public final static int T_ULONG = 0x15; /** -1 0000 long double (special case bit pattern) */ public final static int T_LNGDBL = 0x16; // VARIABLES /** * Symbol name, or pointer into string table if symbol name is greater than * SYMNMLEN. */ private final byte[] _n_name = new byte[SYMNMLEN]; /** long. Symbol's value: dependent on section number, storage class and type. */ private int n_value; /** short, Section number. */ private final short n_scnum; /** Unsigned short. Symbolic type. */ private final int n_type; /** char, Storage class. */ private final byte n_sclass; /** char. Number of auxiliary enties. */ private final byte n_numaux; // CONSTRUCTORS /** * Creates a new Symbol instance. * * @param file * @throws IOException */ protected Symbol(RandomAccessFile file) throws IOException { file.readFully(this._n_name); this.n_value = file.readInt(); this.n_scnum = file.readShort(); this.n_type = file.readUnsignedShort(); this.n_sclass = file.readByte(); this.n_numaux = file.readByte(); } // METHODS /** * @return */ public int getAuxiliaryEntryCount() { return this.n_numaux; } /** * @return */ public String getName() { // For a long name, _n_name[0] == 0 and this would just return empty string. for (int i = 0; i < this._n_name.length; i++) { if (this._n_name[i] == 0) { return new String(this._n_name, 0, i); } } // all eight bytes are filled return new String(this._n_name); } /** * @param aTable * @return */ public String getName(byte[] aTable) { if ((aTable.length > 0) && isLongName()) { // The first four bytes of the string table represent the // number of bytes in the string table. int offset = (((this._n_name[8] & 0xff) << 24) // | ((this._n_name[7] & 0xff) << 16) // | ((this._n_name[6] & 0xff) << 8) // | (this._n_name[5] & 0xff)) - 4; if (offset > 0) { for (int i = offset; i < aTable.length; i++) { if (aTable[i] == 0) { return new String(aTable, offset, i - offset); } } } } return getName(); } /** * @return */ public int getSectionNumber() { return this.n_scnum; } /** * @return */ public byte getStorageClass() { return this.n_sclass; } /** * @return */ public int getType() { return this.n_type; } /** * Returns the current value of n_value. * * @return the n_value */ public int getValue() { return this.n_value; } /** * @return */ public boolean isArray() { return (this.n_type & N_TMASK) == (DT_ARY << N_BTSHFT); } /** * @return */ public boolean isFunction() { return (this.n_type & N_TMASK) == (DT_FCN << N_BTSHFT); } /** * @return */ public boolean isLongName() { return (this._n_name[0] == 0); } /** * /* @since 5.3 * * @return */ public boolean isNoSymbol() { return (this.n_type == T_NULL); } /** * @return */ public boolean isPointer() { return (this.n_type & N_TMASK) == (DT_PTR << N_BTSHFT); } /** * {@inheritDoc} */ @Override public String toString() { return getName(); } /** * @param aOffset */ protected void relocateRelative(int aOffset) { this.n_value += aOffset; } }
5,838
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
SRecordReader.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/hex/SRecordReader.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.hex; import java.io.*; import java.nio.*; import org.flashtool.binutils.hex.util.HexUtils; import org.flashtool.binutils.hex.util.*; /** * Provides a data provider based on a Motorola SRecord file. * * <pre> * S&lt;recordtype&gt;&lt;recordlength&gt;&lt;address&gt;&lt;data&gt;&lt;checksum&gt; * </pre> * <p> * In which is: * </p> * <ul> * <li><b>'S'</b>, the identifying character of the record (therefore called * S-record);</li> * <li><b>recordtype</b>, a character specifying the type of the record: * <ul> * <li>'0': header record with 2 bytes address (value 0); contains usually not * much interesting data, e.g. with the hex encoded text "HEADER";</li> * <li>'1', '2', '3': data record with 2, 3, respectively 4-byte address that * represents the absolute starting address of the first data byte of the * record;</li> * <li>'5': data record count record with a 2-byte address that represents the * preceding number of data records; this record contains no data bytes;</li> * <li>'7', '8', '9': termination record with a 4, 3, respectively 2-byte * address that represents the Entry Point in the terminated data block, so e.g. * the initial value of the program counter of a processor.</li> * </ul> * </li> * <li><b>recordlength</b>, the hex-encoded byte representing the number of * address, data, and checksum bytes;</li> * <li><b>address</b>, the hex-encoded 2, 3, or 4-byte address, depending on the * record type;</li> * <li><b>data</b>, the hex-encoded data bytes (usually not more than 64 per * record, maximum 255);</li> * <li><b>checksum</b>, the one's complement of the sum of all bytes in the * record after the recordtype.</li> * </ul> * <p> * Files with only S0, S1 and S9 records are also called to be in Motorola * Exorcisor format. If also S2 and S8 records appear, the format is also called * Motorola Exormax. * </p> */ public class SRecordReader extends AbstractReader { // CONSTANTS private static final char PREAMBLE = 'S'; // VARIABLES private Integer address; private Integer dataLength; private int dataSum; private boolean inDataRecord; private Integer oldAddress; private int oldDataSum; private Integer oldDataLength; private boolean oldInDataRecord; // CONSTRUCTORS /** * Creates a new SRecordDataProvider instance. * * @param aReader */ public SRecordReader(final Reader aReader) { super(aReader); } // METHODS /** * @see nl.lxtreme.cpemu.util.data.IDataProvider#getAddress() */ @Override public long getAddress() throws IOException { if (this.address == null) { throw new IOException("Unexpected call to getAddress!"); } return this.address; } /** * @see nl.lxtreme.cpemu.util.data.impl.AbstractDataProvider#mark() */ @Override public void mark() throws IOException { super.mark(); this.oldAddress = this.address; this.oldDataSum = this.dataSum; this.oldDataLength = this.dataLength; this.oldInDataRecord = this.inDataRecord; } /** * @see nl.lxtreme.cpemu.util.data.IDataProvider#readByte() */ @Override public int readByte() throws IOException { int ch; do { ch = readSingleByte(); if (ch == -1) { // End-of-file reached; return immediately! return -1; } if (PREAMBLE == ch) { // New record started... this.inDataRecord = isDataRecord(startNewRecord()); } else if (this.dataLength != null) { final int secondHexDigit = this.reader.read(); if (secondHexDigit == -1) { throw new IOException("Unexpected end-of-stream!"); } final char[] buf = { (char) ch, (char) secondHexDigit }; final int dataByte = HexUtils.parseHexByte(buf); if (this.dataLength == 0) { // All data-bytes returned? If so, verify the CRC we've just read... final int calculatedCRC = (~this.dataSum) & 0xFF; if (dataByte != calculatedCRC) { throw new IOException("CRC Error! Expected: " + dataByte + "; got: " + calculatedCRC); } } else { // Decrease the number of hex-bytes we've got to read... this.dataSum += (byte) dataByte; this.dataLength--; this.address++; if (this.inDataRecord) { return dataByte; } } } } while (ch != -1); // We should never come here; it means that we've found a situation that // isn't covered by our loop above... throw new IOException("Invalid Intel HEX-file!"); } /** * @see nl.lxtreme.cpemu.util.data.impl.AbstractDataProvider#reset() */ @Override public void reset() throws IOException { super.reset(); this.address = this.oldAddress; this.dataSum = this.oldDataSum; this.dataLength = this.oldDataLength; this.inDataRecord = this.oldInDataRecord; } /** * @see nl.lxtreme.cpemu.util.data.impl.AbstractDataProvider#getByteOrder() */ @Override protected ByteOrder getByteOrder() { return ByteOrder.BIG_ENDIAN; } /** * Returns the address length in number of bytes of a given SRecord-type. * * @param aType * the SRecord-type to return the address length for. * @return the address length as number of bytes. */ private int getAddressLength(final int aType) { int result = 2; if ((aType == 2) || (aType == 8)) { result = 3; } else if ((aType == 3) || (aType == 7)) { result = 4; } return result; } /** * @param aType * the integer (srecord-)type; * @return <code>true</code> if the given (srecord-)type is a data record, * otherwise <code>false</code>. */ private boolean isDataRecord(final int aType) { return (aType == 1) || (aType == 2) || (aType == 3); } /** * @param aType * the integer (srecord-)type; * @return <code>true</code> if the given (srecord-)type is a header record, * otherwise <code>false</code>. */ private boolean isHeaderRecord(final int aType) { return (aType == 0); } /** * Returns whether the given (srecord-)type is valid or not. * * @param aType * the integer (srecord-)type; * @return <code>true</code> if the given (srecord-)type is valid, otherwise * <code>false</code>. */ private boolean isValidType(final int aType) { // (S0, S1, S2, S3, S5, S7, S8, or S9) return ((aType == 0) || (aType == 1) || (aType == 2) || (aType == 3) || (aType == 5) || (aType == 7) || (aType == 8) || (aType == 9)); } /** * */ private int startNewRecord() throws IOException { // First byte is the length of the data record... final int type = this.reader.read() - '0'; if (!isValidType(type)) { throw new IOException("Unknown type: " + type); } // recordLength is representing the number of address, data, and checksum // bytes; final int recordLength = HexUtils.parseHexByte(this.reader); final int addressLength = getAddressLength(type); this.address = HexUtils.parseHexNumber(this.reader, addressLength); // Calculate the first part of the record CRC; which is defined as the // ones-complement of all (non-CRC) items in the record... // record length this.dataSum = (byte) recordLength; // address length this.dataSum += (byte) ((this.address & 0xff000000) >> 24) + (byte) ((this.address & 0xff0000) >> 16) + (byte) ((this.address & 0xff00) >> 8) + (byte) ((this.address & 0xff)); // The real data length... this.dataLength = recordLength - addressLength - 1; if (this.dataLength > 0) { // Make sure NO data is only for records that should have NO data... if (!isDataRecord(type) && !isHeaderRecord(type)) { throw new IOException("Data found while record-type should not have data!"); } this.address--; } else if (this.dataLength == 0) { // Make sure NO data is only for records that should have NO data... if (isDataRecord(type) || isHeaderRecord(type)) { throw new IOException("No data found while record-type should have data!"); } } return type; } }
8,946
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
AbstractReader.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/hex/AbstractReader.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.hex; import java.io.*; import java.nio.*; import org.flashtool.binutils.hex.util.ByteOrderUtils; import org.flashtool.binutils.hex.util.*; /** * */ public abstract class AbstractReader { // VARIABLES protected final Reader reader; // CONSTRUCTORS /** * Creates a new AbstractReader instance. */ public AbstractReader(final Reader aReader) { this.reader = (aReader instanceof BufferedReader) ? (BufferedReader) aReader : new BufferedReader(aReader); } // METHODS /** * Closes this instruction stream. * * @throws IOException * in case of stream I/O problems. */ public void close() throws IOException { this.reader.close(); } /** * @return * @throws IOException */ public abstract long getAddress() throws IOException; /** * Marks the current "position" in the stream. * * @throws IOException * in case of stream I/O problems. * @see #reset() */ public void mark() throws IOException { this.reader.mark(1024); } /** * Reads a number of bytes in the given buffer. * * @return the next byte, can be <code>-1</code> in case an end-of-stream was * encountered. * @throws IOException * in case of stream I/O problems; */ public abstract int readByte() throws IOException; /** * Reads a number of bytes in the given buffer. * * @return the next long word, can be <code>-1</code> in case an end-of-stream * was * encountered. * @throws IOException * in case of stream I/O problems; */ public int readLongWord() throws IOException { final byte[] data = readBytes(4); if (data == null) { return -1; } return (int) ByteOrderUtils.decode(getByteOrder(), data); } /** * Reads a number of bytes in the given buffer. * * @return the next word, can be <code>-1</code> in case an end-of-stream * was encountered. * @throws IOException * in case of stream I/O problems; */ public int readWord() throws IOException { final byte[] data = readBytes(2); if (data == null) { return -1; } return (int) ByteOrderUtils.decode(ByteOrder.LITTLE_ENDIAN, data); } /** * Resets the current "position" in the stream back to the last "marking" * point. * <p> * In case no mark was set, this operation does nothing. * </p> * * @throws IOException * in case of stream I/O problems. * @see #mark() */ public void reset() throws IOException { this.reader.reset(); } /** * Returns the byte order in which this data provider reads its data. * * @return a byte order, never <code>null</code>. */ protected abstract ByteOrder getByteOrder(); /** * Convenience method to read a number of bytes. * * @param aCount * the number of bytes to read, should be > 0. * @return a byte array with the read bytes, can be <code>null</code> in case * an EOF was found. * @throws IOException * in case of I/O problems; * @throws IllegalArgumentException * in case the given count was <= 0. */ protected final byte[] readBytes(final int aCount) throws IOException, IllegalArgumentException { if (aCount <= 0) { throw new IllegalArgumentException("Count cannot be less or equal to zero!"); } final byte[] result = new byte[aCount]; for (int i = 0; i < aCount; i++) { int readByte = readByte(); if (readByte == -1) { return null; } result[i] = (byte) readByte; } return result; } /** * @param aCount * @return * @throws IOException * @throws IllegalArgumentException */ protected final char[] readChars(final int aCount) throws IOException, IllegalArgumentException { if (aCount <= 0) { throw new IllegalArgumentException("Invalid count!"); } final char[] buf = new char[aCount]; if (this.reader.read(buf) != aCount) { throw new IOException("Unexpected end of stream!"); } return buf; } /** * Skips until the end-of-line is found. */ protected final int readSingleByte() throws IOException { int ch; do { ch = this.reader.read(); } while ((ch != -1) && Character.isWhitespace(ch)); return ch; } }
4,985
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
IntelHexReader.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/hex/IntelHexReader.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.hex; import java.io.*; import java.nio.*; import org.flashtool.binutils.hex.util.HexUtils; import org.flashtool.binutils.hex.util.*; /** * Provides a data provider based on a Intel-HEX file. * <p> * A file in the Intel hex-format is a text file containing hexadecimal encoded * data, organised in so-called records: a text line in the following format: * </p> * * <pre> * :&lt;datacount&gt;&lt;address&gt;&lt;recordtype&gt;&lt;data&gt;&lt;checksum&gt; * </pre> * <p> * In which is: * </p> * <ul> * <li><b>':'</b>, the identifying character of the record;</li> * <li><b>datacount</b>, the hex-encoded byte representing the number of data * bytes in the record;</li> * <li><b>address</b>, the hex-encoded 2-byte address;</li> * <li><b>recordtype</b>, hex-encoded byte representing the record type: * <ul> * <li>'00': data record (like the Motorola record type "S1");</li> * <li>'01': termination record (like the Motorola record type "S9");</li> * <li>'02': segment base address record, the first word of data of this record * used as Segment Base Address of the addresses of the next data records; * actual addresses are calculated as: start address := (SegmentBaseAddress*16) * + record start address;</li> * <li>'04': unknown record-type, the first word of data of this record is * interpreted by Binex as Segment Address, the most significant word of the * addresses of the next data records; actual addresses are calculated as: start * address := (SegmentAddress*65536) + record start address;</li> * </ul> * </li> * <li><b>data</b>, the hex-encoded data bytes (maximum 255);</li> * <li><b>checksum</b>, the two's complement of the sum of all bytes in the * record after the identifying character.</li> * </ul> * <p> * Files with only 00, and 01 records are called to be in Intel "Intellec" 8/MDS * format. The Intel MCS86 (Intellec 86) format adds the 02 type records to * that. * </p> */ public class IntelHexReader extends AbstractReader { // CONSTANTS private static final char PREAMBLE = ':'; private static final int DATA_TYPE = 0; private static final int TERMINATION_TYPE = 1; private static final int EXTENDED_SEGMENT_ADDRESS_TYPE = 2; private static final int START_SEGMENT_ADDRESS_TYPE = 3; private static final int EXTENDED_LINEAR_ADDRESS_TYPE = 4; private static final int START_LINEAR_ADDRESS_TYPE = 5; // VARIABLES private Integer segmentBaseAddress; private Integer linearAddress; private Integer address; private Integer dataLength; private int dataSum; private Integer oldAddress; private int oldDataSum; private Integer oldDataLength; // CONSTRUCTORS /** * Creates a new IntelHexDataProvider instance. * * @param aReader * the reader to use. */ public IntelHexReader(final Reader aReader) { super(aReader); } // METHODS /** * @see nl.lxtreme.cpemu.util.data.IDataProvider#getAddress() */ @Override public long getAddress() throws IOException { if (this.address == null) { throw new IOException("Unexpected call to getAddress!"); } return this.address.longValue(); } /** * @see nl.lxtreme.cpemu.util.data.impl.AbstractDataProvider#mark() */ @Override public void mark() throws IOException { super.mark(); this.oldAddress = this.address; this.oldDataSum = this.dataSum; this.oldDataLength = this.dataLength; } /** * @see nl.lxtreme.cpemu.util.data.IDataProvider#readByte() */ @Override public int readByte() throws IOException { int ch; do { ch = readSingleByte(); if (ch == -1) { // End-of-file reached; return immediately! return -1; } if (PREAMBLE == ch) { // New record started... startNewDataRecord(); } else if (this.dataLength != null) { final char[] buf = { (char) ch, (char) this.reader.read() }; if (buf[1] == -1) { // End-of-file reached; return immediately! return -1; } final int dataByte = HexUtils.parseHexByte(buf); if (this.dataLength == 0) { // All data-bytes returned? If so, verify the CRC we've just read... final int calculatedCRC = (~this.dataSum + 1) & 0xFF; if (dataByte != calculatedCRC) { throw new IOException("CRC Error! Expected: 0x" + Integer.toHexString(dataByte) + "; got: 0x" + Integer.toHexString(calculatedCRC)); } } else { // Decrease the number of hex-bytes we've got to read... this.dataSum += (byte) dataByte; this.dataLength--; this.address++; return dataByte; } } } while (ch != -1); // We should never come here; it means that we've found a situation that // isn't covered by our loop above... throw new IOException("Invalid Intel HEX-file!"); } /** * @see nl.lxtreme.cpemu.util.data.impl.AbstractDataProvider#reset() */ @Override public void reset() throws IOException { super.reset(); this.address = this.oldAddress; this.dataSum = this.oldDataSum; this.dataLength = this.oldDataLength; } /** * @see nl.lxtreme.cpemu.util.data.impl.AbstractDataProvider#getByteOrder() */ @Override protected ByteOrder getByteOrder() { return ByteOrder.LITTLE_ENDIAN; } /** * Starts a new data record, calculates the initial address, and checks what * kind of data the record contains. * * @throws IOException * in case of I/O problems. */ private void startNewDataRecord() throws IOException { // First byte is the length of the data record... this.dataLength = HexUtils.parseHexByte(this.reader); // When a segment base address is previously set, calculate the actual // address by OR-ing this base-address with the address of the record... this.address = HexUtils.parseHexWord(this.reader); if ((this.segmentBaseAddress != null) && (this.segmentBaseAddress > 0)) { this.address = this.segmentBaseAddress | this.address; } else if ((this.linearAddress != null) && (this.linearAddress > 0)) { this.address = (this.linearAddress << 16) | this.address; } final int recordType = HexUtils.parseHexByte(this.reader); // Calculate the first part of the record CRC; which is defined as the // ones-complement of all (non-CRC) items in the record... this.dataSum = this.dataLength.byteValue(); this.dataSum += (byte) ((this.address & 0xFF00) >> 8); this.dataSum += (byte) (this.address & 0xFF); this.dataSum += (byte) recordType; if (DATA_TYPE == recordType) { // Ok, found first data item... Adjust address with a single byte in // order to obtain a valid first address... this.address--; } else if (EXTENDED_SEGMENT_ADDRESS_TYPE == recordType) { this.segmentBaseAddress = HexUtils.parseHexWord(this.reader); // Ignore the rest of the data; but calculate the CRC... this.dataLength = 0; } else if (EXTENDED_LINEAR_ADDRESS_TYPE == recordType) { this.linearAddress = HexUtils.parseHexWord(this.reader); // Ignore the rest of the data; but calculate the CRC... this.dataLength = 0; } else if (TERMINATION_TYPE == recordType) { // Ignore the rest of the data; but calculate the CRC... this.dataLength = 0; } else if ((START_LINEAR_ADDRESS_TYPE != recordType) && (START_SEGMENT_ADDRESS_TYPE != recordType)) { throw new IOException("Unknown Intel record type: " + recordType); } } }
8,285
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
Checksum.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/hex/util/Checksum.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.hex.util; /** * Provides two checksum algorithms commonly used in many HEX-files. */ public enum Checksum { ONES_COMPLEMENT, // TWOS_COMPLEMENT, // ; // METHODS /** * Calculates the checksum for the given array of byte-values. * * @param aValues * the values to calculate the checksum for, should be at least two * values. * @return the 8-bit checksum. * @throws IllegalArgumentException * in case the given values were <code>null</code> or did not * contain at least two values. */ public byte calculate(final byte... aValues) throws IllegalArgumentException { if (aValues == null) { throw new IllegalArgumentException("Values cannot be null!"); } if (aValues.length < 2) { throw new IllegalArgumentException("Should have at least two values to calculate the checksum!"); } int sum = 0; for (int value : aValues) { sum += value; } switch (this) { case ONES_COMPLEMENT: return (byte) (~sum); case TWOS_COMPLEMENT: return (byte) (~sum + 1); default: throw new IllegalArgumentException("Unhandled checksum!"); } } /** * Calculates the checksum for the given array of integer-values. * * @param aValues * the values to calculate the checksum for, should be at least two * values. * @return the 16-bit checksum. * @throws IllegalArgumentException * in case the given values were <code>null</code> or did not * contain at least one value. */ public int calculate(final int... aValues) throws IllegalArgumentException { if (aValues == null) { throw new IllegalArgumentException("Values cannot be null!"); } if (aValues.length < 0) { throw new IllegalArgumentException("Should have at least one values to calculate the checksum!"); } int sum = 0; for (int value : aValues) { sum += value; } switch (this) { case ONES_COMPLEMENT: return (~sum) & 0xFFFF; case TWOS_COMPLEMENT: return (~sum + 1) & 0xFFFF; default: throw new IllegalArgumentException("Unhandled checksum!"); } } }
2,829
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
ByteOrderUtils.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/hex/util/ByteOrderUtils.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.hex.util; import java.nio.*; /** * In computing, endianness is the byte (and sometimes bit) ordering used to * represent some kind of data. Typical cases are the order in which integer * values are stored as bytes in computer memory (relative to a given memory * addressing scheme) and the transmission order over a network or other medium. * When specifically talking about bytes, endianness is also referred to simply * as byte order. */ public class ByteOrderUtils { // CONSTRUCTORS private ByteOrderUtils() { // NO-op } // METHODS /** * Creates a (16-bit) word value with the correct byte order. * * @param aMSB * the most significant byte; * @param aLSB * the least significant byte. * @return the 16-bit combination of both given bytes in the order of * endianness. */ public static int createWord(final ByteOrder aByteOrder, final int aMSB, final int aLSB) { if (aByteOrder == ByteOrder.BIG_ENDIAN) { return ((aMSB << 8) & 0xFF00) | (aLSB & 0x00FF); } return ((aLSB << 8) & 0xFF00) | (aMSB & 0x00FF); } /** * Creates a (16-bit) word value with the correct byte order. * * @param aMSB * the most significant byte; * @param aLSB * the least significant byte. * @return the 16-bit combination of both given bytes in the order of * endianness. */ public static int createWord(final int aMSB, final int aLSB) { return createWord(ByteOrder.nativeOrder(), aMSB, aLSB); } /** * Convenience method to create a single value using the given byte values in * a given byte order. * * @param aExpectedByteOrder * the expected byte order; * @param aBytes * the bytes to decode into a single value, their order depends! * @return the word in the expected byte order. */ public static long decode(final ByteOrder aExpectedByteOrder, final byte... aBytes) { final int byteCount = aBytes.length; final int lastByteIdx = byteCount - 1; long result = 0L; if (aExpectedByteOrder == ByteOrder.BIG_ENDIAN) { for (int i = 0; i < byteCount; i++) { result <<= 8; result |= (aBytes[i] & 0xFF); } } else if (aExpectedByteOrder == ByteOrder.LITTLE_ENDIAN) { for (int i = lastByteIdx; i >= 0; i--) { result <<= 8; result |= (aBytes[i] & 0xFF); } } return result; } /** * Switches the order of bytes of the given (16-bit) word value. * <p> * In effect, this method casts a little-endian value to a big-endian value * and the other way around. * </p> * * @param aValue * the (16-bit) word value to switch the byte order for. * @return the given value with the MSB & LSB switched. */ public static int swap16(final int aValue) { return (((aValue & 0x00ff) << 8) | ((aValue & 0xff00) >> 8)); } /** * Switches the order of bytes of the given (32-bit) long word value. * <p> * In effect, this method casts a little-endian value to a big-endian value * and the other way around. * </p> * * @param aValue * the (32-bit) long word value to switch the byte order for. * @return the given value with the MSB & LSB switched. */ public static int swap32(final int aValue) { return ((aValue & 0x000000FF) << 24) | ((aValue & 0x0000FF00) << 8) // | ((aValue & 0xFF000000) >>> 24) | ((aValue & 0x00FF0000) >>> 8); } }
4,100
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
HexUtils.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/hex/util/HexUtils.java
/******************************************************************************* * Copyright (c) 2011, J.W. Janssen * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * J.W. Janssen - Cleanup and make API more OO-oriented. *******************************************************************************/ package org.flashtool.binutils.hex.util; import java.io.*; import java.nio.*; /** * */ public final class HexUtils { // CONSTRUCTORS /** * Creates a new HexUtils instance. */ private HexUtils() { // NO-op } // METHODS /** * Parses the hex-byte in the given character sequence at the given offset. * * @param aInput * the characters to parse as hex-bytes. * @return a byte value. * @throws IllegalArgumentException * in case the given char sequence was <code>null</code>, in case * the given input did not yield a hex-byte, or the requested offset * is outside the boundaries of the given char sequence. */ public static int parseHexByte(final char[] aInput) throws IllegalArgumentException { if (aInput == null) { throw new IllegalArgumentException("Input cannot be null!"); } return parseHexByte(new String(aInput), 0); } /** * Parses the hex-byte in the given character sequence at the given offset. * * @param aInput * the char sequence to parse as hex-bytes; * @param aOffset * the offset in the char sequence to start parsing. * @return a byte value. * @throws IllegalArgumentException * in case the given char sequence was <code>null</code>, in case * the given input did not yield a hex-byte, or the requested offset * is outside the boundaries of the given char sequence. */ public static int parseHexByte(final CharSequence aInput, final int aOffset) throws IllegalArgumentException { if (aInput == null) { throw new IllegalArgumentException("Input cannot be null!"); } try { return (Integer.parseInt(aInput.subSequence(aOffset, aOffset + 2).toString(), 16)); } catch (IndexOutOfBoundsException exception) { throw new IllegalArgumentException("No such offset: " + aOffset + "; length = " + aInput.length()); } catch (NumberFormatException exception) { throw new IllegalArgumentException("Not a hex-digit string: " + aInput); } } /** * Reads two characters from the given reader and parses them as a single * hex-value byte. * * @param aReader * @return * @throws IllegalArgumentException * @throws IOException */ public static int parseHexByte(final Reader aReader) throws IllegalArgumentException, IOException { return parseHexNumber(aReader, 1); } /** * Parses the hex-byte in the given character sequence at the given offset. * * @param aInput * the char sequence to parse as hex-bytes; * @param aOffset * the offset in the char sequence to start parsing. * @return a byte value. * @throws IllegalArgumentException * in case the given char sequence was <code>null</code>, in case * the given input did not yield a hex-byte, or the requested offset * is outside the boundaries of the given char sequence. */ public static int[] parseHexBytes(final CharSequence aInput, final int aOffset, final int aByteCount) throws IllegalArgumentException { if (aInput == null) { throw new IllegalArgumentException("Input cannot be null!"); } if (aByteCount < 0) { throw new IllegalArgumentException("Byte count cannot be less than one!"); } try { final int[] result = new int[aByteCount]; int offset = aOffset; for (int i = 0; i < aByteCount; i++, offset += 2) { result[i] = Integer.parseInt(aInput.subSequence(offset, offset + 2).toString(), 16); } return result; } catch (IndexOutOfBoundsException exception) { throw new IllegalArgumentException("No such offset: " + aOffset + "; length = " + aInput.length()); } catch (NumberFormatException exception) { throw new IllegalArgumentException("Not a hex-digit string!"); } } /** * @param aInput * @param aOffset * @param aByteCount * @return * @throws IllegalArgumentException */ public static int parseHexNumber(final CharSequence aInput, final int aOffset, final int aByteCount) throws IllegalArgumentException { if (aInput == null) { throw new IllegalArgumentException("Input cannot be null!"); } if (aByteCount < 1) { throw new IllegalArgumentException("Byte count cannot be less than one!"); } final int[] addressBytes = parseHexBytes(aInput, aOffset, aByteCount); int address = 0; for (int i = 0; i < aByteCount; i++) { address |= addressBytes[i]; if (i < aByteCount - 1) { address <<= 8; } } return address; } /** * Reads a number of characters from the given reader and parses them as a * hex-value. * * @param aReader * the reader to read the data from; * @param aByteCount * the number of bytes to read (= 2 * amount of actual characters * read). * @return the parsed number. * @throws IllegalArgumentException * in case the given reader was <code>null</code> or the given byte * count was <= 0. * @throws IOException * in case of I/O problems. */ public static int parseHexNumber(final Reader aReader, final int aByteCount) throws IllegalArgumentException, IOException { if (aReader == null) { throw new IllegalArgumentException("Input cannot be null!"); } if (aByteCount <= 0) { throw new IllegalArgumentException("Byte count cannot be less or equal to zero!"); } final char[] buf = new char[2 * aByteCount]; if (aReader.read(buf) != buf.length) { throw new IOException("Unexpected end-of-stream?!"); } int result = 0; for (char element : buf) { int hexdigit = Character.digit(element, 16); if (hexdigit < 0) { throw new IOException("Unexpected character: " + element); } result *= 16; result |= hexdigit; } return result; } /** * Parses the hex-word in the given character sequence at the given offset * assuming it is in big endian byte order. * * @param aInput * the char sequence to parse as hex-bytes; * @param aOffset * the offset in the char sequence to start parsing. * @return a word value, in big endian byte order. * @throws IllegalArgumentException * in case the given char sequence was <code>null</code>, in case * the given input did not yield a hex-byte, or the requested offset * is outside the boundaries of the given char sequence. */ public static int parseHexWord(final char[] aInput) throws IllegalArgumentException { if (aInput == null) { throw new IllegalArgumentException("Input cannot be null!"); } return parseHexWord(new String(aInput), 0); } /** * Parses the hex-word in the given character sequence at the given offset * assuming it is in big endian byte order. * * @param aInput * the char sequence to parse as hex-bytes; * @param aOffset * the offset in the char sequence to start parsing. * @return a word value, in big endian byte order. * @throws IllegalArgumentException * in case the given char sequence was <code>null</code>, in case * the given input did not yield a hex-byte, or the requested offset * is outside the boundaries of the given char sequence. */ public static int parseHexWord(final CharSequence aInput, final int aOffset) throws IllegalArgumentException { if (aInput == null) { throw new IllegalArgumentException("Input cannot be null!"); } try { int msb = Integer.parseInt(aInput.subSequence(aOffset + 0, aOffset + 2).toString(), 16); int lsb = Integer.parseInt(aInput.subSequence(aOffset + 2, aOffset + 4).toString(), 16); return ByteOrderUtils.createWord(ByteOrder.BIG_ENDIAN, msb, lsb); } catch (IndexOutOfBoundsException exception) { throw new IllegalArgumentException("No such offset: " + aOffset + "; length = " + aInput.length()); } catch (NumberFormatException exception) { throw new IllegalArgumentException("Not a hex-digit string!"); } } /** * Reads four characters from the given reader and parses them as a single * hex-value word. * * @param aReader * @return * @throws IllegalArgumentException * @throws IOException */ public static int parseHexWord(final Reader aReader) throws IllegalArgumentException, IOException { return parseHexNumber(aReader, 2); } }
9,293
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
AR.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/ar/AR.java
/******************************************************************************* * Copyright (c) 2011 - J.W. Janssen * * Copyright (c) 2000, 2008 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * Abeer Bagul (Tensilica) - bug 102434 * Anton Leherbauer (Wind River Systems) * J.W. Janssen - Cleanup and some small API changes. *******************************************************************************/ package org.flashtool.binutils.ar; import java.io.*; import java.util.*; /** * Used for parsing standard ELF archive (ar) files. * * Each object within the archive is represented by an ARHeader class. Each of * of these objects can then be turned into an Elf object for performing Elf * class operations. * * @see AREntry */ public class AR { // VARIABLES private final File file; private RandomAccessFile efile; private long stringTableOffset; private Collection<AREntry> headers; // CONSTRUCTORS /** * Creates a new <code>AR</code> object from the contents of * the given file. * * @param aFile * The AR archive file to process. * @throws IllegalArgumentException * in case the given file was <code>null</code>; * @throws IOException * if the given file is not a valid AR archive. */ public AR(final File aFile) throws IOException { if (aFile == null) { throw new IllegalArgumentException("Parameter File cannot be null!"); } this.file = aFile; this.efile = new RandomAccessFile(aFile, "r"); final byte[] hdrBytes = new byte[7]; this.efile.readFully(hdrBytes); if (!AREntry.isARHeader(hdrBytes)) { this.efile.close(); this.efile = null; throw new IOException("Invalid AR archive! No header found."); } this.efile.readLine(); } // METHODS /** * Disposes all resources for this AR archive. */ public void dispose() { try { if (this.efile != null) { this.efile.close(); this.efile = null; } } catch (final IOException exception) { // Ignored... } } /** * Extracts all files from this archive matching the given names. * * @param aOutputDir * the output directory to extract the files to, cannot be * <code>null</code>; * @param aNames * the names of the files to extract, if omitted all files will be * extracted. * @throws IllegalArgumentException * in case the given output directory was <code>null</code>; * @throws IOException * in case of I/O problems. */ public void extractFiles(final File aOutputDir, final String... aNames) throws IOException { if (aOutputDir == null) { throw new IllegalArgumentException("Parameter OutputDir cannot be null!"); } for (final AREntry header : getEntries()) { String fileName = header.getFileName(); if ((aNames != null) && !stringInStrings(aNames, fileName)) { continue; } this.efile.seek(header.getFileOffset()); extractFile(header, new File(aOutputDir, fileName)); } } /** * Returns the name of this archive. * * @return an archive name, never <code>null</code>. */ public String getArchiveName() { return this.file.getName(); } /** * Get an array of all the object file headers for this archive. * * @throws IOException * Unable to process the archive file. * @return An array of headers, one for each object within the archive. * @see AREntry */ public Collection<AREntry> getEntries() throws IOException { if (this.headers == null) { this.headers = loadEntries(); } return Collections.unmodifiableCollection(this.headers); } /** * Returns all names of the entries in this archive. * * @return a collection of entry names, never <code>null</code>. * @throws IOException * in case of I/O problems. */ public Collection<String> getEntryNames() throws IOException { Collection<AREntry> entries = getEntries(); List<String> result = new ArrayList<String>(entries.size()); for (AREntry entry : entries) { result.add(entry.getFileName()); } return Collections.unmodifiableCollection(result); } /** * Reads a file and writes the results to the given writer object. * * @param aWriter * the writer to write the file contents to, cannot be * <code>null</code>; * @param aName * the name of the file to read, cannot be <code>null</code>. * @return <code>true</code> if the file was successfully read, * <code>false</code> otherwise. * @throws IllegalArgumentException * in case either one of the given arguments was <code>null</code>; * @throws IOException * in case of I/O problems. */ public boolean readFile(final Writer aWriter, final String aName) throws IOException { if (aWriter == null) { throw new IllegalArgumentException("Parameter Writer cannot be null!"); } if (aName == null) { throw new IllegalArgumentException("Parameter Name cannot be null!"); } for (final AREntry header : getEntries()) { String name = header.getFileName(); if (aName.equals(name)) { this.efile.seek(header.getFileOffset()); extractFile(header, aWriter); return true; } } return false; } /** * Look up the name stored in the archive's string table based * on the offset given. * * Maintains <code>efile</code> file location. * * @param aOffset * Offset into the string table for first character of the name. * @throws IOException * <code>offset</code> not in string table bounds. */ final String nameFromStringTable(final long aOffset) throws IOException { if (this.stringTableOffset < 0) { throw new IOException("Invalid AR archive! No string table read yet?!"); } final StringBuilder name = new StringBuilder(); final long originalPos = this.efile.getFilePointer(); try { this.efile.seek(this.stringTableOffset + aOffset); byte temp; while ((temp = this.efile.readByte()) != '\n') { name.append((char) temp); } } finally { this.efile.seek(originalPos); } return name.toString(); } /** * {@inheritDoc} */ @Override protected void finalize() throws Throwable { try { dispose(); } finally { super.finalize(); } } /** * Extracts the given entry and writes its data to a given file. * * @param aEntry * the entry to extract; * @param aFile * the file to write the entry data to. * @throws IOException * in case of I/O problems. */ private void extractFile(final AREntry aEntry, final File aFile) throws IOException { final FileWriter fw = new FileWriter(aFile); try { extractFile(aEntry, fw); } finally { try { fw.close(); } catch (final IOException exception) { // Ignore... } } } /** * Extracts the given entry and writes its data to a given file. * * @param aEntry * the entry to extract; * @param aWriter * the {@link Writer} to write the entry data to. * @throws IOException * in case of I/O problems. */ private void extractFile(final AREntry aEntry, final Writer aWriter) throws IOException { try { long bytesToRead = aEntry.getSize(); while (bytesToRead > 0) { final int byteRead = this.efile.read(); if ((byteRead < 0) && (bytesToRead != 0)) { throw new IOException("Invalid AR archive! Premature end of archive?!"); } aWriter.write(byteRead); bytesToRead--; } } finally { try { aWriter.flush(); } catch (final IOException exception) { // Ignore... } } } /** * Load the entries from the archive (if required). * * @return the read entries, never <code>null</code>. */ private Collection<AREntry> loadEntries() throws IOException { final List<AREntry> headers = new ArrayList<AREntry>(); // Check for EOF condition while (this.efile.getFilePointer() < this.efile.length()) { final AREntry header = AREntry.create(this, this.efile); if (!header.isSpecial()) { headers.add(header); } long pos = this.efile.getFilePointer(); if (header.isStringTableSection()) { this.stringTableOffset = pos; } // Compute the location of the next header in the archive. pos += header.getSize(); if ((pos % 2) != 0) { pos++; } this.efile.seek(pos); } return headers; } /** * Searches for a given subject string in a given set of strings. * * @param aSet * the set of strings to search; * @param aSubject * the subject to search for. * @return <code>true</code> if the given subject was found in the given set, * <code>false</code> otherwise. */ private boolean stringInStrings(final String[] aSet, final String aSubject) { for (final String element : aSet) { if (aSubject.equals(element)) { return true; } } return false; } }
9,933
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
AREntry.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/ar/AREntry.java
/******************************************************************************* * Copyright (c) 2011 - J.W. Janssen * * Copyright (c) 2000, 2008 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * QNX Software Systems - Initial API and implementation * Abeer Bagul (Tensilica) - bug 102434 * Anton Leherbauer (Wind River Systems) * J.W. Janssen - Cleanup and some small API changes. *******************************************************************************/ package org.flashtool.binutils.ar; import java.io.*; /** * The <code>ARHeader</code> class is used to store the per-object file * archive headers. It can also create an Elf object for inspecting * the object file data. */ public class AREntry { // CONSTANTS private static final int NAME_IDX = 0; private static final int NAME_LEN = 16; private static final int MTIME_IDX = 16; private static final int MTIME_LEN = 12; private static final int UID_IDX = 28; private static final int UID_LEN = 6; private static final int GID_IDX = 34; private static final int GID_LEN = 6; private static final int MODE_IDX = 40; private static final int MODE_LEN = 8; private static final int SIZE_IDX = 48; private static final int SIZE_LEN = 10; private static final int MAGIC_IDX = 58; @SuppressWarnings("unused") private static final int MAGIC_LEN = 2; private static final int HEADER_LEN = 60; // VARIABLES private String fileName; private long fileOffset; private long modificationTime; private int uid; private int gid; private int mode; private long size; // CONSTRUCTORS /** * Creates a new archive header object. */ private AREntry() { super(); } // METHODS /** * Factory method to create a {@link AREntry} for the given {@link AR} * archive. * * @param aArchive * the archive to read the header for; * @param aFile * the file of the archive to read the header from. * @return the newly read header, never <code>null</code>. * @throws IOException * in case of I/O problems. */ static AREntry create(final AR aArchive, final RandomAccessFile aFile) throws IOException { final AREntry result = new AREntry(); byte[] buf = new byte[HEADER_LEN]; // Read in the archive header data. Fixed sizes. aFile.readFully(buf); // Save this location so we can create the Elf object later. result.fileOffset = aFile.getFilePointer(); // Convert the raw bytes into strings and numbers. result.fileName = new String(buf, NAME_IDX, NAME_LEN).trim(); result.size = Long.parseLong(new String(buf, SIZE_IDX, SIZE_LEN).trim()); if (!result.isSpecial()) { result.modificationTime = Long.parseLong(new String(buf, MTIME_IDX, MTIME_LEN).trim()); result.uid = Integer.parseInt(new String(buf, UID_IDX, UID_LEN).trim()); result.gid = Integer.parseInt(new String(buf, GID_IDX, GID_LEN).trim()); result.mode = Integer.parseInt(new String(buf, MODE_IDX, MODE_LEN).trim(), 8); if ((buf[MAGIC_IDX] != 0x60) && (buf[MAGIC_IDX + 1] != 0x0A)) { throw new IOException("Not a valid AR archive! No file header magic found."); } } // If the name is something like "#1/<num>", then we're dealing with a BSD // ar file. The <num> is the actual file name length, and the file name // itself is available directly after the header... if (result.isBSDArExtendedFileName()) { try { final int fileNameLength = Integer.parseInt(result.fileName.substring(3)); if (fileNameLength > 0) { buf = new byte[fileNameLength]; aFile.readFully(buf); result.fileName = new String(buf).trim(); } } catch (final NumberFormatException exception) { throw new IOException("Invalid AR archive! (BSD) Extended filename invalid?!"); } } // If the name is of the format "/<number>", we're dealing with a GNU ar // file and we should get name from the string table... if (result.isGNUArExtendedFileName()) { try { final long offset = Long.parseLong(result.fileName.substring(1)); result.fileName = aArchive.nameFromStringTable(offset); } catch (final NumberFormatException exception) { throw new IOException("Invalid AR archive! (GNU) Extended filename invalid?!"); } } // Strip the trailing / from the object name. final int len = result.fileName.length(); if ((len > 2) && (result.fileName.charAt(len - 1) == '/')) { result.fileName = result.fileName.substring(0, len - 1); } return result; } /** * Determines whether the given byte array contains the global AR header, * consisting of the string "!<arch>". * * @param aIdent * the byte array with the possible AR header. * @return <code>true</code> if the given byte array contains the AR header, * <code>false</code> otherwise. */ static boolean isARHeader(final byte[] aIdent) { if ((aIdent.length < 7) || (aIdent[0] != '!') || (aIdent[1] != '<') || (aIdent[2] != 'a') || (aIdent[3] != 'r') || (aIdent[4] != 'c') || (aIdent[5] != 'h') || (aIdent[6] != '>')) { return false; } return true; } /** * {@inheritDoc} */ @Override public boolean equals(Object aObject) { if (this == aObject) { return true; } if ((aObject == null) || (getClass() != aObject.getClass())) { return false; } final AREntry other = (AREntry) aObject; if (this.fileName == null) { if (other.fileName != null) { return false; } } else if (!this.fileName.equals(other.fileName)) { return false; } if (this.fileOffset != other.fileOffset) { return false; } if (this.gid != other.gid) { return false; } if (this.mode != other.mode) { return false; } if (this.modificationTime != other.modificationTime) { return false; } if (this.size != other.size) { return false; } if (this.uid != other.uid) { return false; } return true; } /** * Returns UNIX file mode, containing the permissions of the file. * * @return the mode, should be interpreted as octal value. */ public int getFileMode() { return this.mode; } /** * Get the name of the object file */ public String getFileName() { return this.fileName; } /** * Returns the group ID of the file. * * @return the group ID, as integer value, >= 0. */ public int getGID() { return this.gid; } /** * Returns the timestamp of the file. * * @return the timestamp, as epoch time. */ public long getModificationTime() { return this.modificationTime; } /** * Get the size of the object file . */ public long getSize() { return this.size; } /** * Returns the user ID of the file. * * @return the user ID, as integer value, >= 0. */ public int getUID() { return this.uid; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (this.modificationTime ^ (this.modificationTime >>> 32)); result = prime * result + ((this.fileName == null) ? 0 : this.fileName.hashCode()); result = prime * result + (int) (this.fileOffset ^ (this.fileOffset >>> 32)); result = prime * result + (int) (this.size ^ (this.size >>> 32)); result = prime * result + this.gid; result = prime * result + this.mode; result = prime * result + this.uid; return result; } /** * Returns whether this header represents a special file. * * @return <code>true</code> if this header represents a special file, * <code>false</code> otherwise. */ public boolean isSpecial() { return this.fileName.charAt(0) == '/'; } /** * Returns whether this header represents the string table section. * * @return <code>true</code> if this header represents a string table section, * <code>false</code> otherwise. */ public boolean isStringTableSection() { return this.fileName.equals("//"); } /** * Returns the file offset in the complete binary. * * @return a file offset (in bytes), >= 0. */ final long getFileOffset() { return this.fileOffset; } /** * Returns whether this header is created by BSD ar, and represents an * extended filename. * * @return <code>true</code> if this header is an extended filename created by * BSD ar, <code>false</code> otherwise. */ final boolean isBSDArExtendedFileName() { return this.fileName.matches("^#1/\\d+$"); } /** * Returns whether this header is created by GNU ar, and represents an * extended filename. * * @return <code>true</code> if this header is an extended filename created by * GNU ar, <code>false</code> otherwise. */ final boolean isGNUArExtendedFileName() { return this.fileName.matches("^/\\d+$"); } }
9,554
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
UsbEndpointDescriptor.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/libusb/UsbEndpointDescriptor.java
package org.flashtool.libusb; import org.flashtool.jna.libusb.libusb_endpoint_descriptor; import lombok.extern.slf4j.Slf4j; @Slf4j public class UsbEndpointDescriptor { private byte endpoint; private String direction; public UsbEndpointDescriptor(libusb_endpoint_descriptor endpoint) { this.endpoint = endpoint.bEndpointAddress; if ((endpoint.bEndpointAddress & 0x80) > 0) { this.direction = "in"; } else this.direction = "out"; } public boolean isIn() { return this.direction.equals("in"); } public boolean isOut() { return this.direction.equals("out"); } public byte getEndpoint() { return this.endpoint; } }
680
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
UsbDevList.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/libusb/UsbDevList.java
package org.flashtool.libusb; import java.util.Iterator; import java.util.Vector; import lombok.extern.slf4j.Slf4j; @Slf4j public class UsbDevList { Vector<UsbDevice> list = new Vector<UsbDevice>(); public void addDevice(UsbDevice d) { try { d.setConfiguration(); d.ref(); list.add(d); } catch (Exception e) {}; } public Iterator<UsbDevice> getDevices() { return list.iterator(); } public void destroyDevices() { Iterator<UsbDevice> i = getDevices(); while (i.hasNext()) { try { i.next().destroy(); } catch (LibUsbException e) {} } list.clear(); } public int size() { return list.size(); } public UsbDevice get(int index) { return list.get(index); } }
710
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
UsbInterfaceDescriptor.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/libusb/UsbInterfaceDescriptor.java
package org.flashtool.libusb; import java.util.Vector; import org.flashtool.jna.libusb.libusb_endpoint_descriptor; import org.flashtool.jna.libusb.libusb_interface_descriptor; import lombok.extern.slf4j.Slf4j; @Slf4j public class UsbInterfaceDescriptor { private byte alternateSetting; private Vector<UsbEndpointDescriptor> endpoints = new Vector(); public UsbInterfaceDescriptor(libusb_interface_descriptor iface_desc) { this.alternateSetting = iface_desc.bAlternateSetting; if (iface_desc.bNumEndpoints > 0) { libusb_endpoint_descriptor[] endpoints = (libusb_endpoint_descriptor[])iface_desc.endpoint.toArray(iface_desc.bNumEndpoints); for (libusb_endpoint_descriptor endpoint : endpoints) this.endpoints.add(new UsbEndpointDescriptor(endpoint)); } } int getId() { return this.alternateSetting; } public int getNbEndpointDescriptors() { return this.endpoints.size(); } public Vector<UsbEndpointDescriptor> getEndpointDescriptors() { return this.endpoints; } }
1,035
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
UsbConfiguration.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/libusb/UsbConfiguration.java
package org.flashtool.libusb; import java.util.Vector; import org.flashtool.jna.libusb.libusb_config_descriptor; import org.flashtool.jna.libusb.libusb_interface; import lombok.extern.slf4j.Slf4j; @Slf4j public class UsbConfiguration { Vector<UsbInterface> ifaces = new Vector(); int id; public UsbConfiguration(libusb_config_descriptor cdesc) { this.id = cdesc.bConfigurationValue; if (cdesc.bNumInterfaces > 0) { libusb_interface[] ifaces = (libusb_interface[])cdesc.iFaces.toArray(cdesc.bNumInterfaces); int iid = 0; for (libusb_interface iface : ifaces) this.ifaces.add(new UsbInterface(iid++, iface)); } } public int getNbInterfaces() { return this.ifaces.size(); } public Vector<UsbInterface> getInterfaces() { return this.ifaces; } public int getId() { return this.id; } }
860
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
UsbDevice.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/libusb/UsbDevice.java
package org.flashtool.libusb; import com.sun.jna.Pointer; import com.sun.jna.ptr.PointerByReference; import java.util.Iterator; import java.util.Vector; import org.flashtool.jna.libusb.LibUsbLibrary; import org.flashtool.jna.libusb.libusb_config_descriptor; import org.flashtool.jna.libusb.libusb_device_descriptor; import lombok.extern.slf4j.Slf4j; @Slf4j public class UsbDevice { private Pointer usb_device = null; private Pointer handle = null; private String vendorid = ""; private String productid = ""; private byte iSerialNumber; private byte iManufacturer; private Vector<UsbConfiguration> confs = new Vector(); private int iface_detached = -1; private int iface_claimed = -1; private int refcount=0; private byte default_endpoint_in=0, default_endpoint_out=0; private int nbconfig=0; public UsbDevice(Pointer device) throws LibUsbException { this.usb_device = device; libusb_device_descriptor[] arr = new libusb_device_descriptor[1]; int result = LibUsbLibrary.libUsb.libusb_get_device_descriptor(this.usb_device, arr); UsbSystem.checkError("get_device_descriptor", result); this.vendorid = String.format("%4s", new Object[] { Integer.toHexString(arr[0].idVendor & 0xFFFF) }).replace(' ', '0'); this.productid = String.format("%4s", new Object[] { Integer.toHexString(arr[0].idProduct & 0xFFFF) }).replace(' ', '0'); this.iSerialNumber = arr[0].iSerialNumber; this.iManufacturer = arr[0].iManufacturer; nbconfig = arr[0].bNumConfigurations; } public String getVendor() { return this.vendorid; } public String getProduct() { return this.productid; } public int getNbConfig() { return this.confs.size(); } public void unref() { LibUsbLibrary.libUsb.libusb_unref_device(this.usb_device); refcount--; } public void ref() { LibUsbLibrary.libUsb.libusb_ref_device(this.usb_device); refcount++; } public void close() throws LibUsbException { if (handle != null) { releaseInterface(); LibUsbLibrary.libUsb.libusb_close(this.handle); this.handle = null; refcount--; } } public void open() throws Exception { Pointer[] dev_handle = new Pointer[1]; int result = LibUsbLibrary.libUsb.libusb_open(this.usb_device, dev_handle); int retries=0; int maxretries=5; if (result == LibUsbLibrary.libusb_error.LIBUSB_ERROR_NO_DEVICE || result == LibUsbLibrary.libusb_error.LIBUSB_ERROR_NOT_FOUND || result == LibUsbLibrary.libusb_error.LIBUSB_ERROR_OTHER) throw new Exception("Error while querying the device"); if (result <0) { while (retries<maxretries) { try { Thread.sleep(500); } catch (Exception e) {}; result = LibUsbLibrary.libUsb.libusb_open(this.usb_device, dev_handle); if (result == LibUsbLibrary.libusb_error.LIBUSB_ERROR_NO_DEVICE || result == LibUsbLibrary.libusb_error.LIBUSB_ERROR_NOT_FOUND || result == LibUsbLibrary.libusb_error.LIBUSB_ERROR_OTHER) { this.handle=null; throw new Exception("Error while querying the device"); } if (result==0) retries=maxretries; retries++; } } UsbSystem.checkError("Open", result); if (result == 0) { this.handle = dev_handle[0]; refcount++; } else this.handle=null; } public void openAndClaim(int iface) throws Exception { open(); claimInterface(iface); } public void releaseAndClose() throws LibUsbException { releaseInterface(); close(); } public String getSerial() throws LibUsbException { byte[] buffer = new byte[256]; if (handle!=null) { int result = LibUsbLibrary.libUsb.libusb_get_string_descriptor_ascii(this.handle, this.iSerialNumber, buffer, buffer.length); if (result == LibUsbLibrary.libusb_error.LIBUSB_ERROR_INVALID_PARAM) return ""; UsbSystem.checkError("libusb_get_string_descriptor_ascii", result); return new String(buffer); } else return ""; } public String getManufacturer() throws LibUsbException { byte[] buffer = new byte[256]; if (handle!=null) { int result = LibUsbLibrary.libUsb.libusb_get_string_descriptor_ascii(this.handle, this.iManufacturer, buffer, buffer.length); if (result == LibUsbLibrary.libusb_error.LIBUSB_ERROR_INVALID_PARAM) return ""; UsbSystem.checkError("libusb_get_string_descriptor_ascii", result); return new String(buffer); } else return ""; } public void setConfiguration() throws Exception { PointerByReference configRef = new PointerByReference(); int result = LibUsbLibrary.libUsb.libusb_get_config_descriptor(this.usb_device, 0, configRef); int retries=0; int maxretries=5; if (result <0) { while (retries<maxretries) { try { Thread.sleep(500); } catch (Exception e) {}; result = LibUsbLibrary.libUsb.libusb_get_config_descriptor(this.usb_device, 0, configRef); if (result==0) retries=maxretries; retries++; } } UsbSystem.checkError("get_config", result); if (result<0) throw new Exception("setConfiguration error"); libusb_config_descriptor cd = new libusb_config_descriptor(configRef.getValue()); libusb_config_descriptor[] cdescs = cd.toArray(nbconfig); for (libusb_config_descriptor cdesc : cdescs) { this.confs.add(new UsbConfiguration(cdesc)); } LibUsbLibrary.libUsb.libusb_free_config_descriptor(configRef.getValue()); Iterator iconfs = getConfigurations().iterator(); while (iconfs.hasNext()) { UsbConfiguration c = (UsbConfiguration)iconfs.next(); Iterator ifaces = c.getInterfaces().iterator(); while (ifaces.hasNext()) { UsbInterface iface = (UsbInterface)ifaces.next(); Iterator<UsbInterfaceDescriptor>ifdescs = iface.getInterfaceDescriptors().iterator(); while (ifdescs.hasNext()) { UsbInterfaceDescriptor ifdesc = ifdescs.next(); Iterator endpoints = ifdesc.getEndpointDescriptors().iterator(); while (endpoints.hasNext()) { UsbEndpointDescriptor endpoint = (UsbEndpointDescriptor)endpoints.next(); if (endpoint.isIn()) default_endpoint_in = endpoint.getEndpoint(); else default_endpoint_out = endpoint.getEndpoint(); } } } } } public Vector<UsbConfiguration> getConfigurations() { return this.confs; } public void claimInterface(int ifacenum) throws LibUsbException { if (handle != null) { int result = LibUsbLibrary.libUsb.libusb_claim_interface(this.handle, ifacenum); UsbSystem.checkError("claim_interface", result); if (result != 0) { result = LibUsbLibrary.libUsb.libusb_detach_kernel_driver(this.handle, ifacenum); UsbSystem.checkError("detach kernel", result); this.iface_detached = ifacenum; result = LibUsbLibrary.libUsb.libusb_claim_interface(this.handle, ifacenum); UsbSystem.checkError("claim_interface", result); } iface_claimed = ifacenum; } } public void releaseInterface() throws LibUsbException { if (handle != null && iface_claimed>=0) { int result = LibUsbLibrary.libUsb.libusb_release_interface(this.handle, iface_claimed); UsbSystem.checkError("release_interface", result); if (result==0) iface_claimed = -1; if (this.iface_detached >= 0) { result = LibUsbLibrary.libUsb.libusb_attach_kernel_driver(this.handle, this.iface_detached); UsbSystem.checkError("attach kernel", result); } } } public byte[] bulkRead(int count) throws LibUsbException { if (handle != null) { byte[] data = new byte[count]; int[] actual_length = new int[1]; int result = LibUsbLibrary.libUsb.libusb_bulk_transfer(this.handle, default_endpoint_in, data, data.length, actual_length, 10000); int retries=0; if (result <0) { while (retries<2) { result = LibUsbLibrary.libUsb.libusb_bulk_transfer(this.handle, default_endpoint_in, data, data.length, actual_length, 10000); if (result==0) retries=3; retries++; } } UsbSystem.checkError("libusb_bulk_transfer (read)", result); if (result>=0) return getReply(data, actual_length[0]); else return null; } else return null; } public void bulkWrite(byte[] data) throws LibUsbException { if (handle != null) { int[] actual_length = new int[1]; int result = LibUsbLibrary.libUsb.libusb_bulk_transfer(this.handle, default_endpoint_out, data, data.length, actual_length, 0); UsbSystem.checkError("libusb_bulk_transfer (write)", result); if (data.length != actual_length[0]) System.err.println("Error : did not write all data"); } } public byte[] getReply(byte[] reply, int nbread) { if (reply.length == nbread) return reply; byte[] newreply = null; if (nbread > 0) { newreply = new byte[nbread]; System.arraycopy(reply, 0, newreply, 0, nbread); } return newreply; } public void destroy() throws LibUsbException { close(); if (refcount>0) { while (refcount>0) unref(); } } }
9,004
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
LibUsbException.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/libusb/LibUsbException.java
package org.flashtool.libusb; import lombok.extern.slf4j.Slf4j; @Slf4j public class LibUsbException extends Exception { /** * */ private static final long serialVersionUID = 1L; public LibUsbException(String msg){ super(msg); } public LibUsbException(String msg, Throwable t){ super(msg,t); } }
334
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
UsbSystem.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/libusb/UsbSystem.java
package org.flashtool.libusb; import org.flashtool.jna.libusb.LibUsbLibrary; import org.flashtool.jna.libusb.libusb_version; import com.sun.jna.Pointer; import lombok.extern.slf4j.Slf4j; @Slf4j public class UsbSystem { Pointer context = null; byte endpoint_in; byte endpoint_out; String version; public UsbSystem() throws LibUsbException { initSystem(); } public void initSystem() throws LibUsbException { Pointer[] p = new Pointer[1]; try { int result = LibUsbLibrary.libUsb.libusb_init(p); checkError("init", result); this.context = p[0]; //LibUsbLibrary.libUsb.libusb_set_debug(this.context, 4); } catch (UnsatisfiedLinkError e) { throw new LibUsbException("Libusb not found. Minimum libusb version is 1.0.15. It can be downloaded on http://www.libusbx.org"); } try { libusb_version v = LibUsbLibrary.libUsb.libusb_get_version(); if (v.major!=(short)1 || v.minor!=(short)0 || v.micro<(short)15) { throw new LibUsbException("Minimum libusb version is 1.0.15. Found "+v.major + "." + v.minor + "." + v.micro); } version=v.major+"."+v.minor+"."+v.micro; } catch (UnsatisfiedLinkError e) { throw new LibUsbException("A libusb was found but not with the right version. Minimum libusb version is 1.0.15. It can be downloaded on http://www.libusbx.org"); } } public String getVersion() { return version; } public UsbDevList getDevices(String vendorid) throws LibUsbException{ UsbDevList list = new UsbDevList(); Pointer[] devs = new Pointer[1]; int result = LibUsbLibrary.libUsb.libusb_get_device_list(null, devs); checkError("libusb_get_device_list",result); Pointer[] devices = devs[0].getPointerArray(0L); UsbDevice device = null; for (Pointer usb_device : devices) { if (usb_device != null) { device = new UsbDevice(usb_device); if (device.getVendor().equals(vendorid)) { list.addDevice(device); } } } LibUsbLibrary.libUsb.libusb_free_device_list(devs[0], 1); return list; /*if (device != null) { System.out.println(device.getVendor() + ":" + device.getProduct()); System.out.println("Serial : " + device.getSerial()); System.out.println("Device Configuration :"); System.out.println("Number of configurations " + device.getNbConfig()); Iterator iconfs = device.getConfigurations().iterator(); while (iconfs.hasNext()) { UsbConfiguration c = (UsbConfiguration)iconfs.next(); System.out.println(" Configuration number " + c.getId() + " with " + c.getNbInterfaces() + " interfaces"); Iterator ifaces = c.getInterfaces().iterator(); while (ifaces.hasNext()) { UsbInterface iface = (UsbInterface)ifaces.next(); System.out.println(" Number of alternate settings for interface " + iface.getId() + " : " + iface.getNbInterfaceDescriptors()); Iterator<UsbInterfaceDescriptor>ifdescs = iface.getInterfaceDescriptors().iterator(); while (ifdescs.hasNext()) { UsbInterfaceDescriptor ifdesc = ifdescs.next(); System.out.println(" Number of endpoints for alternate setting " + ifdesc.getId() + " : " + ifdesc.getNbEndpointDescriptors()); Iterator endpoints = ifdesc.getEndpointDescriptors().iterator(); while (endpoints.hasNext()) { UsbEndpointDescriptor endpoint = (UsbEndpointDescriptor)endpoints.next(); if (endpoint.isIn()) this.endpoint_in = endpoint.getEndpoint(); else this.endpoint_out = endpoint.getEndpoint(); System.out.print(" " + (endpoint.isIn() ? "In :" : "Out :")); System.out.println("0x" + Integer.toHexString(endpoint.getEndpoint() & 0xFF)); } } } } byte[] data = null; System.out.println("Reading from device :"); System.out.println("First read"); data = device.bulkRead(); System.out.println("Second read"); data = device.bulkRead(); if (data != null) { System.out.println("Reply :"); System.out.println(new String(data)); } System.out.println("Third read"); data = device.bulkRead(); S1Packet cmd1 = new S1Packet(1, new byte[0], false); System.out.println("Writing to device : " + HexDump.toHex(cmd1.getByteArray())); device.bulkWrite(cmd1.getByteArray()); System.out.println("Reading from device :"); System.out.print("First read : "); data = device.bulkRead(); System.out.print("Second read : "); data = device.bulkRead(); if (data != null) { System.out.println(data.length); System.out.println("Reply :"); String dataS = new String(data); if (dataS.indexOf(";IMEI=")>0) System.out.println(dataS.substring(0, dataS.indexOf(";IMEI=")) + dataS.substring(dataS.indexOf(";MSN="))); else System.out.println(dataS); } System.out.println("Third read : "); data = device.bulkRead(); device.close(); device.destroy(); }*/ } public void endSystem() { LibUsbLibrary.libUsb.libusb_exit(this.context); } public static void checkError(String action, int error) throws LibUsbException { switch (error) { case -1: throw new LibUsbException(action + " : I/O Errors"); case -2: throw new LibUsbException(action + " : Invalid parameters"); case -3: throw new LibUsbException(action + " : Access error. No permission on device"); case -4: throw new LibUsbException(action + " : No device"); case -5: throw new LibUsbException(action + " : Device Not found"); case -6: throw new LibUsbException(action + " : Device busy"); case -7: throw new LibUsbException(action + " : Timeout"); case -8: throw new LibUsbException(action + " : Overflow"); case -9: throw new LibUsbException(action + " : Pipe error"); case -10: throw new LibUsbException(action + " : Interrupted by user"); case -11: throw new LibUsbException(action + " : No memory"); case -12: throw new LibUsbException(action + " : Not supported"); case -99: throw new LibUsbException(action + " : Other"); } } }
6,252
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
UsbInterface.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/libusb/UsbInterface.java
package org.flashtool.libusb; import java.util.Vector; import org.flashtool.jna.libusb.libusb_interface; import org.flashtool.jna.libusb.libusb_interface_descriptor; import lombok.extern.slf4j.Slf4j; @Slf4j public class UsbInterface { Vector<UsbInterfaceDescriptor> ifacesdesc = new Vector(); int id; public UsbInterface(int id, libusb_interface iface) { this.id = id; if (iface.num_altsetting > 0) { libusb_interface_descriptor[] iface_descs = (libusb_interface_descriptor[])iface.altsetting.toArray(iface.num_altsetting); for (libusb_interface_descriptor iface_desc : iface_descs) this.ifacesdesc.add(new UsbInterfaceDescriptor(iface_desc)); } } public int getId() { return this.id; } public int getNbInterfaceDescriptors() { return this.ifacesdesc.size(); } public Vector<UsbInterfaceDescriptor> getInterfaceDescriptors() { return this.ifacesdesc; } }
930
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
FlashtoolAppender.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/ch/qos/logback/core/FlashtoolAppender.java
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.core; import static ch.qos.logback.core.CoreConstants.CODES_URL; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Scanner; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.io.FileUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Display; import org.flashtool.logger.MyLogger; import ch.qos.logback.classic.Level; import ch.qos.logback.core.encoder.Encoder; import ch.qos.logback.core.encoder.LayoutWrappingEncoder; import ch.qos.logback.core.joran.spi.ConsoleTarget; import ch.qos.logback.core.spi.DeferredProcessingAware; import ch.qos.logback.core.status.ErrorStatus; import ch.qos.logback.core.status.Status; import ch.qos.logback.core.status.WarnStatus; import ch.qos.logback.core.util.Loader; /** * OutputStreamAppender appends events to a {@link OutputStream}. This class * provides basic services that other appenders build upon. * * For more information about this appender, please refer to the online manual * at http://logback.qos.ch/manual/appenders.html#OutputStreamAppender * * @author Ceki G&uuml;lc&uuml; */ public class FlashtoolAppender<E> extends UnsynchronizedAppenderBase<E> { protected ConsoleTarget target = ConsoleTarget.SystemOut; protected boolean withJansi = false; private final static String AnsiConsole_CLASS_NAME = "org.fusesource.jansi.AnsiConsole"; private final static String wrapSystemOut_METHOD_NAME = "wrapSystemOut"; private final static String wrapSystemErr_METHOD_NAME = "wrapSystemErr"; private final static Class<?>[] ARGUMENT_TYPES = { PrintStream.class }; private StyledText text = null; private ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); private BufferedOutputStream boutputStream = new BufferedOutputStream(byteStream); /** * It is the encoder which is ultimately responsible for writing the event to an * {@link OutputStream}. */ protected Encoder<E> encoder; /** * All synchronization in this class is done via the lock object. */ protected final ReentrantLock lock = new ReentrantLock(false); /** * This is the {@link OutputStream outputStream} where output will be written. */ private OutputStream outputStream; boolean immediateFlush = true; /** * Sets the value of the <b>Target</b> option. Recognized values are * "System.out" and "System.err". Any other value will be ignored. */ public void setTarget(String value) { ConsoleTarget t = ConsoleTarget.findByName(value.trim()); if (t == null) { targetWarn(value); } else { target = t; } } /** * Returns the current value of the <b>target</b> property. The default value of * the option is "System.out". * <p> * See also {@link #setTarget}. */ public String getTarget() { return target.getName(); } private void targetWarn(String val) { Status status = new WarnStatus("[" + val + "] should be one of " + Arrays.toString(ConsoleTarget.values()), this); status.add(new WarnStatus("Using previously set target, System.out by default.", this)); addStatus(status); } /** * The underlying output stream used by this appender. * * @return */ public OutputStream getOutputStream() { return outputStream; } /** * Checks that requires parameters are set and if everything is in order, * activates this appender. */ public void start() { OutputStream targetStream = target.getStream(); // enable jansi only if withJansi set to true if (withJansi) { targetStream = wrapWithJansi(targetStream); } setOutputStream(targetStream); int errors = 0; if (this.encoder == null) { addStatus(new ErrorStatus("No encoder set for the appender named \"" + name + "\".", this)); errors++; } if (this.outputStream == null) { addStatus(new ErrorStatus("No output stream set for the appender named \"" + name + "\".", this)); errors++; } // only error free appenders should be activated if (errors == 0) { super.start(); } } private OutputStream wrapWithJansi(OutputStream targetStream) { try { addInfo("Enabling JANSI AnsiPrintStream for the console."); ClassLoader classLoader = Loader.getClassLoaderOfObject(context); Class<?> classObj = classLoader.loadClass(AnsiConsole_CLASS_NAME); String methodName = target == ConsoleTarget.SystemOut ? wrapSystemOut_METHOD_NAME : wrapSystemErr_METHOD_NAME; Method method = classObj.getMethod(methodName, ARGUMENT_TYPES); return (OutputStream) method.invoke(null, new PrintStream(targetStream)); } catch (Exception e) { addWarn("Failed to create AnsiPrintStream. Falling back on the default stream.", e); } return targetStream; } /** * @return whether to use JANSI or not. */ public boolean isWithJansi() { return withJansi; } /** * If true, this appender will output to a stream provided by the JANSI library. * * @param withJansi whether to use JANSI or not. * @since 1.0.5 */ public void setWithJansi(boolean withJansi) { this.withJansi = withJansi; } public void setLayout(Layout<E> layout) { addWarn("This appender no longer admits a layout as a sub-component, set an encoder instead."); addWarn("To ensure compatibility, wrapping your layout in LayoutWrappingEncoder."); addWarn("See also " + CODES_URL + "#layoutInsteadOfEncoder for details"); LayoutWrappingEncoder<E> lwe = new LayoutWrappingEncoder<E>(); lwe.setLayout(layout); lwe.setContext(context); this.encoder = lwe; } @Override protected void append(E eventObject) { if (!isStarted()) { return; } subAppend(eventObject); } /** * Stop this appender instance. The underlying stream or writer is also closed. * * <p> * Stopped appenders cannot be reused. */ public void stop() { if(!isStarted()) return; lock.lock(); try { closeOutputStream(); super.stop(); } finally { lock.unlock(); } } /** * Close the underlying {@link OutputStream}. */ protected void closeOutputStream() { if (this.outputStream != null) { try { // before closing we have to output out layout's footer encoderClose(); this.outputStream.close(); this.outputStream = null; } catch (IOException e) { addStatus(new ErrorStatus("Could not close output stream for OutputStreamAppender.", this, e)); } } } void encoderClose() { if (encoder != null && this.outputStream != null) { try { byte[] footer = encoder.footerBytes(); writeBytes(footer); } catch (IOException ioe) { this.started = false; addStatus(new ErrorStatus("Failed to write footer for appender named [" + name + "].", this, ioe)); } } } /** * <p> * Sets the @link OutputStream} where the log output will go. The specified * <code>OutputStream</code> must be opened by the user and be writable. The * <code>OutputStream</code> will be closed when the appender instance is * closed. * * @param outputStream An already opened OutputStream. */ public void setOutputStream(OutputStream outputStream) { lock.lock(); try { // close any previously opened output stream closeOutputStream(); this.outputStream = outputStream; if (encoder == null) { addWarn("Encoder has not been set. Cannot invoke its init method."); return; } encoderInit(); } finally { lock.unlock(); } } void encoderInit() { if (encoder != null && this.outputStream != null) { try { byte[] header = encoder.headerBytes(); writeBytes(header); } catch (IOException ioe) { this.started = false; addStatus( new ErrorStatus("Failed to initialize encoder for appender named [" + name + "].", this, ioe)); } } } protected void writeOut(E event) throws IOException { byte[] byteArray = this.encoder.encode(event); writeBytes(byteArray); Display.getDefault().syncExec(new Runnable() { public void run() { // Append formatted message to textarea. if (MyLogger.getLevel()==Level.ERROR) { append(text.getDisplay().getSystemColor(SWT.COLOR_RED),new String(byteArray)); } else if (MyLogger.getLevel()==Level.WARN) { append(text.getDisplay().getSystemColor(SWT.COLOR_BLUE),new String(byteArray)); } else { append(text.getDisplay().getSystemColor(SWT.COLOR_BLACK),new String(byteArray)); } } }); } public void append(final Color color, final String message) { text.append(message); StyleRange styleRange = new StyleRange(); styleRange.start = text.getCharCount()-message.length(); styleRange.length = message.length(); styleRange.fontStyle = SWT.NORMAL; styleRange.foreground = color; text.setStyleRange(styleRange); text.setSelection(text.getCharCount()); } private void writeBytes(byte[] byteArray) throws IOException { if (byteArray == null || byteArray.length == 0) return; lock.lock(); try { if (text==null) this.outputStream.write(byteArray); this.boutputStream.write(byteArray); if (immediateFlush) { if (text==null) this.outputStream.flush(); this.boutputStream.flush(); } } finally { lock.unlock(); } } /** * Actual writing occurs here. * <p> * Most subclasses of <code>WriterAppender</code> will need to override this * method. * * @since 0.9.0 */ protected void subAppend(E event) { if (!isStarted()) { return; } try { // this step avoids LBCLASSIC-139 if (event instanceof DeferredProcessingAware) { ((DeferredProcessingAware) event).prepareForDeferredProcessing(); } writeOut(event); } catch (IOException ioe) { // as soon as an exception occurs, move to non-started state // and add a single ErrorStatus to the SM. this.started = false; addStatus(new ErrorStatus("IO failure in appender", this, ioe)); } } public Encoder<E> getEncoder() { return encoder; } public void setEncoder(Encoder<E> encoder) { this.encoder = encoder; } public boolean isImmediateFlush() { return immediateFlush; } public void setImmediateFlush(boolean immediateFlush) { this.immediateFlush = immediateFlush; } public void setStyledText(StyledText text) { lock.lock(); boolean first=false; if (this.text==null) first=true; this.text=text; if (first) { Scanner sc = new Scanner(getContent()); while (sc.hasNextLine()) { String line = sc.nextLine(); Display.getDefault().syncExec(new Runnable() { public void run() { // Append formatted message to textarea. if (line.contains("ERROR")) { append(text.getDisplay().getSystemColor(SWT.COLOR_RED),line+"\n"); } else if (line.contains("WARN")) { append(text.getDisplay().getSystemColor(SWT.COLOR_BLUE),line+"\n"); } else { append(text.getDisplay().getSystemColor(SWT.COLOR_BLACK),line+"\n"); } } }); } } lock.unlock(); } public String getContent() { try { return byteStream.toString("UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } public void writeFile(String fname) { final File file = new File(fname); try { FileUtils.writeStringToFile(file, getContent(), Charset.forName("UTF-8")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setMode(String mode) { /* if (!mode.equals(this.mode)) { log.info("Changing mode from "+this.mode + " to "+mode); this.mode=mode; }*/ } }
13,973
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
Env.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/Env.java
package org.meteordev.meteorbot; public enum Env { DISCORD_TOKEN("DISCORD_TOKEN"), API_BASE("API_BASE"), BACKEND_TOKEN("BACKEND_TOKEN"), GUILD_ID("GUILD_ID"), COPE_NN_ID("COPE_NN_ID"), MEMBER_COUNT_ID("MEMBER_COUNT_ID"), DOWNLOAD_COUNT_ID("DOWNLOAD_COUNT_ID"), UPTIME_URL("UPTIME_URL"); public final String value; Env(String key) { this.value = System.getenv(key); } }
424
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
MeteorBot.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/MeteorBot.java
package org.meteordev.meteorbot; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.channel.ChannelType; import net.dv8tion.jda.api.entities.emoji.Emoji; import net.dv8tion.jda.api.entities.emoji.RichCustomEmoji; import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.session.ReadyEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.utils.cache.CacheFlag; import net.dv8tion.jda.internal.utils.JDALogger; import org.jetbrains.annotations.NotNull; import org.meteordev.meteorbot.command.Commands; import org.slf4j.Logger; public class MeteorBot extends ListenerAdapter { private static final String[] HELLOS = {"hi", "hello", "howdy", "bonjour", "ciao", "hej", "hola", "yo"}; public static final Logger LOG = JDALogger.getLog("Meteor Bot"); private Guild server; private RichCustomEmoji copeEmoji; public static void main(String[] args) { String token = Env.DISCORD_TOKEN.value; if (token == null) { MeteorBot.LOG.error("Must specify discord bot token."); return; } JDABuilder.createDefault(token) .enableIntents(GatewayIntent.GUILD_MEMBERS, GatewayIntent.MESSAGE_CONTENT) .enableCache(CacheFlag.EMOJI) .addEventListeners(new MeteorBot(), new Commands(), new Uptime(), new InfoChannels()) .build(); } @Override public void onReady(ReadyEvent event) { JDA bot = event.getJDA(); bot.getPresence().setActivity(Activity.playing("Meteor Client")); server = bot.getGuildById(Env.GUILD_ID.value); if (server == null) { MeteorBot.LOG.error("Couldn't find the specified server."); System.exit(1); } copeEmoji = server.getEmojiById(Env.COPE_NN_ID.value); LOG.info("Meteor Bot started"); } @Override public void onMessageReceived(MessageReceivedEvent event) { if (!event.isFromType(ChannelType.TEXT) || !event.isFromGuild() || !event.getGuild().equals(server)) return; String content = event.getMessage().getContentRaw(); if (!content.contains(event.getJDA().getSelfUser().getAsMention())) return; for (String hello : HELLOS) { if (content.toLowerCase().contains(hello)) { event.getMessage().reply(hello + " :)").queue(); return; } } event.getMessage().addReaction(content.toLowerCase().contains("cope") ? copeEmoji : Emoji.fromUnicode("\uD83D\uDC4B")).queue(); } @Override public void onGuildMemberJoin(@NotNull GuildMemberJoinEvent event) { if (Env.BACKEND_TOKEN.value == null) return; Utils.apiPost("discord/userJoined").queryString("id", event.getMember().getId()).asEmpty(); } @Override public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { if (Env.BACKEND_TOKEN.value == null) return; Utils.apiPost("discord/userLeft").asEmpty(); } }
3,368
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
InfoChannels.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/InfoChannels.java
package org.meteordev.meteorbot; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel; import net.dv8tion.jda.api.events.session.ReadyEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.LongSupplier; public class InfoChannels extends ListenerAdapter { private static final int UPDATE_PERIOD = 6; private static int delay; @Override public void onReady(ReadyEvent event) { Guild guild = event.getJDA().getGuildById(Env.GUILD_ID.value); if (guild == null) { MeteorBot.LOG.warn("Failed to fetch guild when initialising info channels."); return; } if (Env.MEMBER_COUNT_ID.value == null || Env.DOWNLOAD_COUNT_ID.value == null) { MeteorBot.LOG.warn("Must define info channel id's for them to function."); return; } VoiceChannel memberCount = guild.getVoiceChannelById(Env.MEMBER_COUNT_ID.value); VoiceChannel downloads = guild.getVoiceChannelById(Env.DOWNLOAD_COUNT_ID.value); if (memberCount == null || downloads == null) { MeteorBot.LOG.warn("Failed to fetch channels when initialising info channels."); return; } updateChannel(downloads, () -> Utils.apiGet("stats").asJson().getBody().getObject().getLong("downloads")); updateChannel(memberCount, guild::getMemberCount); } private static void updateChannel(VoiceChannel channel, LongSupplier supplier) { Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> { String name = channel.getName(); name = "%s %s".formatted(name.substring(0, name.lastIndexOf(':') + 1), Utils.formatLong(supplier.getAsLong())); channel.getManager().setName(name).complete(); }, delay, UPDATE_PERIOD, TimeUnit.MINUTES); delay += UPDATE_PERIOD / 2; } }
2,013
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
Uptime.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/Uptime.java
package org.meteordev.meteorbot; import kong.unirest.Unirest; import net.dv8tion.jda.api.events.session.ReadyEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import org.jetbrains.annotations.NotNull; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Uptime extends ListenerAdapter { @Override public void onReady(@NotNull ReadyEvent event) { if (Env.UPTIME_URL.value == null) { MeteorBot.LOG.warn("Uptime URL not configured, uptime requests will not be made"); return; } Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> { String url = Env.UPTIME_URL.value; if (url.endsWith("ping=")) url += event.getJDA().getGatewayPing(); Unirest.get(url).asEmpty(); }, 0, 60, TimeUnit.SECONDS); } }
864
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
Utils.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/Utils.java
package org.meteordev.meteorbot; import kong.unirest.GetRequest; import kong.unirest.HttpRequestWithBody; import kong.unirest.Unirest; import net.dv8tion.jda.api.EmbedBuilder; import java.awt.*; import java.text.NumberFormat; import java.time.temporal.ChronoUnit; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class Utils { private static final Pattern TIME_PATTERN = Pattern.compile("^(\\d+)(ms|s|m|h|d|w)$"); private static final Color COLOR = new Color(145, 61, 226); private static final String[] SUFFIXES = {"k", "m", "b", "t"}; private Utils() { } public static long parseAmount(String parse) { Matcher matcher = TIME_PATTERN.matcher(parse); if (!matcher.matches() || matcher.groupCount() != 2) return -1; try { return Integer.parseInt(matcher.group(1)); } catch (NumberFormatException ignored) { return -1; } } public static ChronoUnit parseUnit(String parse) { Matcher matcher = TIME_PATTERN.matcher(parse); if (!matcher.matches() || matcher.groupCount() != 2) return null; return unitFromString(matcher.group(2)); } public static ChronoUnit unitFromString(String string) { for (ChronoUnit value : ChronoUnit.values()) { String stringValue = unitToString(value); if (stringValue == null) continue; if (stringValue.equalsIgnoreCase(string)) { return value; } } return null; } public static String unitToString(ChronoUnit unit) { return switch (unit) { case SECONDS -> "s"; case MINUTES -> "m"; case HOURS -> "h"; case DAYS -> "d"; case WEEKS -> "w"; default -> null; }; } public static String formatLong(long value) { String formatted = NumberFormat.getNumberInstance(Locale.UK).format(value); String first = formatted, second = "", suffix = ""; if (formatted.contains(",")) { int firstComma = formatted.indexOf(','); first = formatted.substring(0, firstComma); second = "." + formatted.substring(firstComma + 1, firstComma + 3); suffix = SUFFIXES[formatted.replaceAll("[^\",\"]", "").length() - 1]; } return first + second + suffix; } public static EmbedBuilder embedTitle(String title, String format, Object... args) { return new EmbedBuilder().setColor(COLOR).setTitle(title).setDescription(String.format(format, args)); } public static EmbedBuilder embed(String format, Object... args) { return embedTitle(null, format, args); } public static GetRequest apiGet(String path) { return Unirest.get(Env.API_BASE.value + path); } public static HttpRequestWithBody apiPost(String path) { return Unirest.post(Env.API_BASE.value + path).header("Authorization", Env.BACKEND_TOKEN.value); } }
3,048
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
Commands.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/Commands.java
package org.meteordev.meteorbot.command; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.session.ReadyEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; import org.jetbrains.annotations.NotNull; import org.meteordev.meteorbot.Env; import org.meteordev.meteorbot.MeteorBot; import org.meteordev.meteorbot.command.commands.LinkCommand; import org.meteordev.meteorbot.command.commands.StatsCommand; import org.meteordev.meteorbot.command.commands.help.FaqCommand; import org.meteordev.meteorbot.command.commands.help.InstallationCommand; import org.meteordev.meteorbot.command.commands.help.LogsCommand; import org.meteordev.meteorbot.command.commands.help.OldVersionCommand; import org.meteordev.meteorbot.command.commands.moderation.BanCommand; import org.meteordev.meteorbot.command.commands.moderation.CloseCommand; import org.meteordev.meteorbot.command.commands.moderation.MuteCommand; import org.meteordev.meteorbot.command.commands.moderation.UnmuteCommand; import org.meteordev.meteorbot.command.commands.silly.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Commands extends ListenerAdapter { private static final Map<String, Command> BOT_COMMANDS = new HashMap<>(); public static void add(Command command) { BOT_COMMANDS.put(command.name, command); } @Override public void onReady(@NotNull ReadyEvent event) { add(new FaqCommand()); add(new InstallationCommand()); add(new LogsCommand()); add(new OldVersionCommand()); add(new BanCommand()); add(new CloseCommand()); add(new MuteCommand()); add(new UnmuteCommand()); add(new CapyCommand()); add(new CatCommand()); add(new DogCommand()); add(new MonkeyCommand()); add(new PandaCommand()); add(new StatsCommand()); if (Env.BACKEND_TOKEN.value != null) { add(new LinkCommand()); } List<CommandData> commandData = new ArrayList<>(); for (Command command : BOT_COMMANDS.values()) { commandData.add(command.build(new CommandDataImpl(command.name, command.description))); } event.getJDA().updateCommands().addCommands(commandData).complete(); MeteorBot.LOG.info("Loaded {} commands", BOT_COMMANDS.size()); } @Override public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) { Command command = BOT_COMMANDS.get(event.getName()); if (command == null) return; command.run(event); } }
2,807
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
Command.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/Command.java
package org.meteordev.meteorbot.command; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; public abstract class Command { public final String name, description; protected Command(String name, String description) { this.name = name; this.description = description; } public abstract SlashCommandData build(SlashCommandData data); public abstract void run(SlashCommandInteractionEvent event); public static Member parseMember(SlashCommandInteractionEvent event) { OptionMapping memberOption = event.getOption("member"); if (memberOption == null || memberOption.getAsMember() == null) { event.reply("Couldn't find that member.").setEphemeral(true).queue(); return null; } Member member = memberOption.getAsMember(); if (member == null) event.reply("Couldn't find that member.").setEphemeral(true).queue(); return member; } }
1,162
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
StatsCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/StatsCommand.java
package org.meteordev.meteorbot.command.commands; import kong.unirest.json.JSONObject; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import org.meteordev.meteorbot.Utils; import org.meteordev.meteorbot.command.Command; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.regex.Pattern; public class StatsCommand extends Command { private static final Pattern DATE_PATTERN = Pattern.compile("\\d{2}-\\d{2}-\\d{4}"); public StatsCommand() { super("stats", "Shows various stats about Meteor."); } @Override public SlashCommandData build(SlashCommandData data) { return data.addOption(OptionType.STRING, "date", "The date to fetch stats for."); } @Override public void run(SlashCommandInteractionEvent event) { String date; OptionMapping option = event.getOption("date"); if (option != null && DATE_PATTERN.matcher(option.getAsString()).matches()) { date = option.getAsString(); } else { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.setTime(new Date()); date = "%02d-%02d-%d".formatted(calendar.get(Calendar.DATE), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.YEAR)); } if (date == null) { event.reply("Failed to determine date.").setEphemeral(true).queue(); return; } JSONObject json = Utils.apiGet("stats").queryString("date", date).asJson().getBody().getObject(); if (json == null || json.has("error")) { event.reply("Failed to fetch stats for this date.").setEphemeral(true).queue(); return; } int joins = json.getInt("joins"), leaves = json.getInt("leaves"); event.replyEmbeds(Utils.embed("**Date**: %s\n**Joins**: %d\n**Leaves**: %d\n**Gained**: %d\n**Downloads**: %d".formatted(json.getString("date"), joins, leaves, joins - leaves, json.getInt("downloads"))).build()).queue(); } }
2,265
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
LinkCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/LinkCommand.java
package org.meteordev.meteorbot.command.commands; import kong.unirest.json.JSONObject; import net.dv8tion.jda.api.entities.channel.ChannelType; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import org.meteordev.meteorbot.Utils; import org.meteordev.meteorbot.command.Command; public class LinkCommand extends Command { public LinkCommand() { super("link", "Links your Discord account to your Meteor account."); } @Override public SlashCommandData build(SlashCommandData data) { return data.addOption(OptionType.STRING, "token", "The token generated on the Meteor website.", true); } @Override public void run(SlashCommandInteractionEvent event) { if (!event.getChannel().getType().equals(ChannelType.PRIVATE)) { event.reply("This action must be in DMs.").setEphemeral(true).queue(); return; } OptionMapping token = event.getOption("token"); if (token == null || token.getAsString().isBlank()) { event.reply("Must specify a valid token.").setEphemeral(true).queue(); return; } JSONObject json = Utils.apiPost("account/linkDiscord") .queryString("id", event.getUser().getId()) .queryString("token", token.getAsString()) .asJson().getBody().getObject(); if (json.has("error")) { event.reply("Failed to link your Discord account. Try generating a new token by refreshing the account page and clicking the link button again.").setEphemeral(true).queue(); return; } event.reply("Successfully linked your Discord account.").setEphemeral(true).queue(); } }
1,921
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
HelpCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/help/HelpCommand.java
package org.meteordev.meteorbot.command.commands.help; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import net.dv8tion.jda.api.interactions.components.ItemComponent; import org.meteordev.meteorbot.command.Command; public abstract class HelpCommand extends Command { protected final ItemComponent[] components; protected final String message; protected HelpCommand(String name, String description, String message, ItemComponent... components) { super(name, description); this.message = message; this.components = components == null ? new ItemComponent[0] : components; } @Override public SlashCommandData build(SlashCommandData data) { return data.addOption(OptionType.USER, "member", "The member to ping.", true); } @Override public void run(SlashCommandInteractionEvent event) { Member member = parseMember(event); if (member == null) return; event.reply("%s %s".formatted(member.getAsMention(), message)).addActionRow(components).queue(); } }
1,265
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
OldVersionCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/help/OldVersionCommand.java
package org.meteordev.meteorbot.command.commands.help; import net.dv8tion.jda.api.interactions.components.buttons.Button; public class OldVersionCommand extends HelpCommand { public OldVersionCommand() { super( "old-versions", "Tells someone how to play on old versions", "Please read the old versions guide before asking more questions.", Button.link("https://meteorclient.com/faq/old-versions", "Guide") ); } }
487
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
LogsCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/help/LogsCommand.java
package org.meteordev.meteorbot.command.commands.help; import net.dv8tion.jda.api.interactions.components.buttons.Button; public class LogsCommand extends HelpCommand { public LogsCommand() { super( "logs", "Tells someone how to find their logs", "Please read the guide for sending logs before asking more questions.", Button.link("https://meteorclient.com/faq/getting-log", "Guide") ); } }
465
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
InstallationCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/help/InstallationCommand.java
package org.meteordev.meteorbot.command.commands.help; import net.dv8tion.jda.api.interactions.components.buttons.Button; public class InstallationCommand extends HelpCommand { public InstallationCommand() { super( "installation", "Tells someone to read the installation guide", "Please read the installation guide before asking more questions.", Button.link("https://meteorclient.com/faq/installation", "Guide") ); } }
494
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
FaqCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/help/FaqCommand.java
package org.meteordev.meteorbot.command.commands.help; import net.dv8tion.jda.api.interactions.components.buttons.Button; public class FaqCommand extends HelpCommand { public FaqCommand() { super( "faq", "Tells someone to read the faq", "The FAQ answers your question, please read it.", Button.link("https://meteorclient.com/faq", "FAQ") ); } }
419
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
CapyCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/silly/CapyCommand.java
package org.meteordev.meteorbot.command.commands.silly; import kong.unirest.Unirest; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import org.meteordev.meteorbot.command.Command; public class CapyCommand extends Command { public CapyCommand() { super("capybara", "pulls up"); } @Override public SlashCommandData build(SlashCommandData data) { return data; } @Override public void run(SlashCommandInteractionEvent event) { Unirest.get("https://api.capy.lol/v1/capybara?json=true").asJsonAsync(response -> { event.reply(response.getBody().getObject().getJSONObject("data").getString("url")).queue(); }); } }
797
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
DogCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/silly/DogCommand.java
package org.meteordev.meteorbot.command.commands.silly; import kong.unirest.Unirest; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import org.meteordev.meteorbot.command.Command; public class DogCommand extends Command { public DogCommand() { super("dog", "dawg"); } @Override public SlashCommandData build(SlashCommandData data) { return data; } @Override public void run(SlashCommandInteractionEvent event) { Unirest.get("https://some-random-api.com/img/dog").asJsonAsync(response -> { event.reply(response.getBody().getObject().getString("link")).queue(); }); } }
758
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
MonkeyCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/silly/MonkeyCommand.java
package org.meteordev.meteorbot.command.commands.silly; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import org.meteordev.meteorbot.command.Command; import java.util.concurrent.ThreadLocalRandom; public class MonkeyCommand extends Command { public MonkeyCommand() { super("monkey", "Sends a swag monkey."); } @Override public SlashCommandData build(SlashCommandData data) { return data; } @Override public void run(SlashCommandInteractionEvent event) { int w = ThreadLocalRandom.current().nextInt(200, 1001); int h = ThreadLocalRandom.current().nextInt(200, 1001); event.reply("https://www.placemonkeys.com/" + w + "/" + h + "?random").queue(); } }
839
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
CatCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/silly/CatCommand.java
package org.meteordev.meteorbot.command.commands.silly; import kong.unirest.Unirest; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import org.meteordev.meteorbot.command.Command; public class CatCommand extends Command { public CatCommand() { super("cat", "gato"); } @Override public SlashCommandData build(SlashCommandData data) { return data; } @Override public void run(SlashCommandInteractionEvent event) { Unirest.get("https://some-random-api.com/img/cat").asJsonAsync(response -> { event.reply(response.getBody().getObject().getString("link")).queue(); }); } }
758
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
PandaCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/silly/PandaCommand.java
package org.meteordev.meteorbot.command.commands.silly; import kong.unirest.Unirest; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import org.meteordev.meteorbot.command.Command; import java.util.concurrent.ThreadLocalRandom; public class PandaCommand extends Command { public PandaCommand() { super("panda", "funny thing"); } @Override public SlashCommandData build(SlashCommandData data) { return data; } @Override public void run(SlashCommandInteractionEvent event) { String animal = ThreadLocalRandom.current().nextBoolean() ? "red_panda" : "panda"; Unirest.get("https://some-random-api.com/img/" + animal).asJsonAsync(response -> { event.reply(response.getBody().getObject().getString("link")).queue(); }); } }
917
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
MuteCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/moderation/MuteCommand.java
package org.meteordev.meteorbot.command.commands.moderation; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; import org.meteordev.meteorbot.Utils; import org.meteordev.meteorbot.command.Command; import java.time.Duration; import java.time.temporal.ChronoUnit; public class MuteCommand extends Command { public MuteCommand() { super("mute", "Mutes a user for a maximum of 27 days."); } @Override public SlashCommandData build(SlashCommandData data) { return data .addOption(OptionType.USER, "member", "The member to mute.", true) .addOption(OptionType.STRING, "duration", "The duration of the mute.", true) .addOption(OptionType.STRING, "reason", "The reason for the mute.") .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.MODERATE_MEMBERS)); } @Override public void run(SlashCommandInteractionEvent event) { Member member = parseMember(event); if (member == null) return; if (member.isTimedOut()) { event.reply("That user is already timed out.").setEphemeral(true).queue(); return; } if (member.hasPermission(Permission.MODERATE_MEMBERS)) { event.reply("That member can't be muted.").setEphemeral(true).queue(); return; } String duration = event.getOption("duration").getAsString(); long amount = Utils.parseAmount(duration); ChronoUnit unit = Utils.parseUnit(duration); if (amount == -1 || unit == null) { event.reply("Failed to parse mute duration.").setEphemeral(true).queue(); return; } if (unit == ChronoUnit.SECONDS && amount < 10) { event.reply("Please input a minimum duration of 10 seconds.").setEphemeral(true).queue(); return; } String reason = ""; OptionMapping reasonOption = event.getOption("reason"); if (reasonOption != null) reason = reasonOption.getAsString(); AuditableRestAction<Void> action = member.timeoutFor(Duration.of(amount, unit)); if (!reason.isBlank()) action.reason(reason); action.queue(a -> { event.reply("Timed out %s for %s.".formatted(member.getAsMention(), duration)).queue(); }); } }
2,780
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
UnmuteCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/moderation/UnmuteCommand.java
package org.meteordev.meteorbot.command.commands.moderation; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import org.meteordev.meteorbot.command.Command; public class UnmuteCommand extends Command { public UnmuteCommand() { super("unmute", "Unmutes the specified member."); } @Override public SlashCommandData build(SlashCommandData data) { return data.addOption(OptionType.USER, "member", "The member to unmute.", true) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.MODERATE_MEMBERS)); } @Override public void run(SlashCommandInteractionEvent event) { Member member = parseMember(event); if (member == null) return; if (!member.isTimedOut()) { event.reply("Member isn't already muted.").setEphemeral(true).queue(); return; } member.removeTimeout().queue(a -> { event.reply("Removed timeout for %s.".formatted(member.getAsMention())).queue(); }); } }
1,356
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
CloseCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/moderation/CloseCommand.java
package org.meteordev.meteorbot.command.commands.moderation; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.channel.ChannelType; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import org.meteordev.meteorbot.command.Command; public class CloseCommand extends Command { public CloseCommand() { super("close", "Locks the current forum post"); } @Override public SlashCommandData build(SlashCommandData data) { return data; } @Override public void run(SlashCommandInteractionEvent event) { if (event.getChannelType() != ChannelType.GUILD_PUBLIC_THREAD) { event.reply("This command can only be used in a forum post.").setEphemeral(true).queue(); return; } if (!event.getMember().hasPermission(Permission.MANAGE_THREADS)) { event.reply("You don't have permission to lock threads.").setEphemeral(true).queue(); return; } event.reply("This post is now locked.").queue(hook -> { event.getChannel().asThreadChannel().getManager().setLocked(true).setArchived(true).queue(); }); } }
1,272
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
BanCommand.java
/FileExtraction/Java_unseen/MeteorDevelopment_meteor-bot/src/main/java/org/meteordev/meteorbot/command/commands/moderation/BanCommand.java
package org.meteordev.meteorbot.command.commands.moderation; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; import org.meteordev.meteorbot.command.Command; import java.util.concurrent.TimeUnit; public class BanCommand extends Command { public BanCommand() { super("ban", "Bans a member"); } @Override public SlashCommandData build(SlashCommandData data) { return data .addOption(OptionType.USER, "member", "The member to ban.", true) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.BAN_MEMBERS)); } @Override public void run(SlashCommandInteractionEvent event) { if (!event.getMember().hasPermission(Permission.BAN_MEMBERS)) { event.reply("You don't have permission to ban members.").setEphemeral(true).queue(); return; } Member member = parseMember(event); if (member == null) return; member.ban(0, TimeUnit.NANOSECONDS).queue(a -> { event.reply("Banned %s.".formatted(member.getAsMention())).queue(); }); } }
1,425
Java
.java
MeteorDevelopment/meteor-bot
10
9
4
2020-11-03T15:29:45Z
2024-01-09T16:59:55Z
MessageDigestProviderImplTest.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/test/java/org/gzipper/java/application/hashing/MessageDigestProviderImplTest.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.hashing; import org.junit.Test; import java.util.EnumMap; import static org.junit.Assert.assertEquals; /** * * @author Matthias Fussenegger */ public class MessageDigestProviderImplTest { /** * The test value of which to compute the hash values. */ private static final String TEST_VALUE = "gzipper"; private final EnumMap<MessageDigestAlgorithm, String> _resultMap; public MessageDigestProviderImplTest() { _resultMap = new EnumMap<>(MessageDigestAlgorithm.class); // expected results for string "gzipper" _resultMap.put(MessageDigestAlgorithm.MD5, "de0f5d52f214223991ad720af4c19bb0"); _resultMap.put(MessageDigestAlgorithm.SHA_1, "8fd5c761ea51947cf14ce83059b7a73e4244ed6c"); _resultMap.put(MessageDigestAlgorithm.SHA_256, "31685001b8f052a6aa701be092231e8" + "f4404bdff1aeb2e0a6214440c16476a5f"); _resultMap.put(MessageDigestAlgorithm.SHA_384, "e6b03411f9ad267f50e841009ab72" + "684a0064441a8f3893f3ae90" + "fba14d5bdebf0b8ce14d58b9" + "48550db8b067dc15c76"); _resultMap.put(MessageDigestAlgorithm.SHA_512, "cfc351af41d6704cf935071d3b5e3ae9d3337" + "e353764416537f3febf45f9183ddb2e9" + "5e4006dc0fc69d3b59e3570f3201fa14" + "3928adc2560e44eaf11ad25d0b7"); } /** * Test of computeHash method, of class MessageDigestProviderImpl. */ @Test public void testComputeHash() { System.out.println("computeHash"); final byte[] bytes = TEST_VALUE.getBytes(); for (MessageDigestAlgorithm algorithm : MessageDigestAlgorithm.values()) { System.out.println(algorithm.name() + " start"); // compute hash value String result = _resultMap.get(algorithm); MessageDigestResult expResult = MessageDigestProvider.computeHash(bytes, algorithm); // only compare hex value since it is calculated from byte array assertEquals(result.toUpperCase(), expResult.toString()); System.out.println(algorithm.name() + " end"); } System.out.println("All tests successful"); } }
3,095
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
CompressionAlgorithmTest.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/test/java/org/gzipper/java/application/algorithm/CompressionAlgorithmTest.java
/* * Copyright (C) 2019 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm; import org.gzipper.java.application.algorithm.TestUtils.TestObject; import org.gzipper.java.application.algorithm.type.*; import org.gzipper.java.application.model.OperatingSystem; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.util.Settings; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.time.LocalDate; import java.time.LocalTime; import java.util.Arrays; import java.util.Iterator; import static org.junit.Assert.*; /** * Test of {@link CompressionAlgorithm} interface and its realizations. * * @author Matthias Fussenegger */ @RunWith(Parameterized.class) public class CompressionAlgorithmTest { // <editor-fold defaultstate="collapsed" desc="setUp attributes"> private String _archiveFileNamePrefix; private String _testFileNamePrefix; // </editor-fold> private final CompressionAlgorithm _algorithm; private final String _printText; private final String _fileNameExtension; private final String _tempDirectory; @Parameters public static Iterable<Object[]> data() { return Arrays.asList(new Object[][]{ {new Zip(), "ZIP test", ".zip"}, {new Jar(), "JAR test", ".jar"}, {new Gzip(), "GZIP test", ".gzip"}, {new Tar(), "TAR test", ".tar"}, {new TarGzip(), "TAR+GZ test", ".tgz"}, {new TarBzip2(), "TAR+BZIP2 test", ".tbz2"}, {new TarLzma(), "TAR+LZMA test", ".tlz"}, {new TarXz(), "TAR+XZ test", ".txz"} }); } public CompressionAlgorithmTest(CompressionAlgorithm algorithm, String printText, String fileNameExtension) throws IOException { _algorithm = algorithm; _printText = printText; _fileNameExtension = fileNameExtension; // create temporary file to determine TEMP folder location File temp = File.createTempFile("gzipper_temp_file", null); _tempDirectory = temp.getAbsoluteFile().getParent(); } @BeforeClass public static void setUpClass() { OperatingSystem os = TestUtils.getOperatingSystem(); Settings.getInstance().init(null, os); } @Before public void setUp() { final LocalTime time = LocalTime.now(); // define name of test archive _archiveFileNamePrefix = "gzipper_aa_test_archive-" + LocalDate.now() + "-" + time.getNano(); _archiveFileNamePrefix = _archiveFileNamePrefix.replaceAll(":", "_"); assertFalse(FileUtils.containsIllegalChars(_archiveFileNamePrefix)); // define name of test file (to be archived) _testFileNamePrefix = "gzipper_aa_test_file-" + LocalDate.now() + "-" + time.getNano(); _testFileNamePrefix = _testFileNamePrefix.replaceAll(":", "_"); assertFalse(FileUtils.containsIllegalChars(_testFileNamePrefix)); } /** * Test of compress and extract method, of class ArchivingAlgorithm. */ @Test public void testCompressExtract() { try { System.out.println(_printText); testCompressionExtraction(_algorithm, _fileNameExtension); } catch (Exception ex) { ex.printStackTrace(); fail(ex.getMessage()); } } private void testCompressionExtraction( CompressionAlgorithm instance, String suffix) throws Exception { final String location = _tempDirectory; final String name = _archiveFileNamePrefix + suffix; final String filename = FileUtils.generateUniqueFilename( location, _archiveFileNamePrefix, suffix, 0); final TestObject testObj = TestUtils .generateTestObject(_tempDirectory, _testFileNamePrefix); final File testFile = testObj._testFile; final File archiveFile = new File(filename); try { System.out.println("compress"); final File[] files = {testFile}; instance.compress(files, location, name); // build output file location final StringBuilder sb = new StringBuilder(location); if (!location.endsWith(File.separator)) { sb.append(File.separator); } System.out.println("extract"); instance.extract(sb.toString(), filename); // build output file name File outputFolder = null; if (!(instance instanceof Gzip)) { // gzip does not create output folder sb.append(_archiveFileNamePrefix); outputFolder = new File(sb.toString()); assertTrue(outputFolder.exists()); sb.append(File.separator); } sb.append(testFile.getName()); final File extractedFile = new File(sb.toString()); assertTrue(extractedFile.exists()); try { // validate extracted file final Iterator<String> iter = testObj._fileContent.linesIterator(); try (FileReader fr = new FileReader(extractedFile); BufferedReader reader = new BufferedReader(fr)) { String line; while ((line = reader.readLine()) != null) { assertTrue(iter.hasNext()); assertEquals(line, iter.next()); } } System.out.println("Test successful"); } finally { extractedFile.delete(); if (outputFolder != null) { outputFolder.delete(); } } } finally { testFile.delete(); archiveFile.delete(); } } }
6,955
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
TestUtils.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/test/java/org/gzipper/java/application/algorithm/TestUtils.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm; import org.gzipper.java.application.model.OS; import org.gzipper.java.application.model.OperatingSystem; import org.gzipper.java.application.util.FileUtils; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; /** * * @author Matthias Fussenegger */ public final class TestUtils { private static final int NUMBER_OF_LINES = 32; private static final int LINE_LENGTH = 256; static String generateRandomString(int length) { final StringBuilder sb = new StringBuilder(length); final Random rand = ThreadLocalRandom.current(); for (int i = 0; i < length; ++i) { char c = (char) (rand.nextInt(126 - 32) + 32); sb.append(c); } return sb.toString(); } static TestObject generateTestObject(String dir, String fname) throws IOException { String filename = FileUtils.combine(dir, fname); File file = File.createTempFile(filename, null); Document document = new Document(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { for (int i = 0; i < NUMBER_OF_LINES; ++i) { String line = TestUtils.generateRandomString(LINE_LENGTH); writer.append(line); document.appendLine(line); writer.newLine(); writer.flush(); } } return new TestObject(file, document); } static OperatingSystem getOperatingSystem() { return System.getProperty("os.name") .toLowerCase().startsWith("windows") ? new OperatingSystem(OS.WINDOWS) : new OperatingSystem(OS.UNIX); } static class Document { final List<String> _lines; private Document() { _lines = new ArrayList<>(); } void appendLine(String line) { _lines.add(line); } Iterator<String> linesIterator() { return _lines.iterator(); } } static class TestObject { final File _testFile; final Document _fileContent; private TestObject(File testFile, Document fileContent) { _testFile = testFile; _fileContent = fileContent; } } }
3,203
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
module-info.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/module-info.java
/* * Copyright (C) 2020 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ module org.gzipper { opens org.gzipper.java.presentation to javafx.graphics; opens org.gzipper.java.presentation.controller to javafx.fxml; opens org.gzipper.java.presentation.controller.main to javafx.fxml; // standard-lib modules requires java.logging; // third-party modules requires org.apache.commons.compress; requires org.tukaani.xz; requires javafx.baseEmpty; requires javafx.base; requires javafx.controlsEmpty; requires javafx.controls; requires javafx.fxmlEmpty; requires javafx.fxml; requires javafx.graphicsEmpty; requires javafx.graphics; requires kotlin.stdlib; }
1,344
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
GZipperException.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/exceptions/GZipperException.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.exceptions; import java.io.Serial; /** * Class to handle application specific errors. * * @author Matthias Fussenegger */ public class GZipperException extends Exception { @Serial private static final long serialVersionUID = 5822293002523982761L; private Reason _reason = Reason.UNKNOWN; /** * Delegates error message to its super class {@link Exception}. * * @param errorMessage the specified error message. */ public GZipperException(String errorMessage) { super(errorMessage); } /** * Delegates exception cause to its super class {@link Exception}. * * @param cause the cause of this exception. */ public GZipperException(Throwable cause) { super(cause); } /** * Creates a new {@link GZipperException} including a reason. * * @param reason the reason of this exception. * @param msg the specified error message. * @return a new instance of {@link GZipperException}. */ public static GZipperException createWithReason(Reason reason, String msg) { GZipperException ex = new GZipperException(msg); ex.setReason(reason); return ex; } /** * Returns the reason of this exception. * * @return the reason of this exception. */ public Reason getReason() { return _reason; } /** * Sets the reason of this exception if it is not {@code null}. If the * provided parameter is {@code null}, the reason will be set to its default * value, which is {@code UNKNOWN}. * * @param reason the reason of this exception. */ public void setReason(Reason reason) { _reason = reason == null ? Reason.UNKNOWN : reason; } /** * The reason of the exception. */ public enum Reason { NO_DIR_SUPPORTED, FAULTY_COMPRESSION_LVL, ILLEGAL_MODE, UNKNOWN } }
2,733
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
ProgressManager.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/ProgressManager.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; /** * Manages progress values and calculates the total progress on an update. Also holds the current progress, which can * be a sentinel value. Beside calculating the total progress, the purpose of this class is to provide a solution for * the flooding of the UI thread, which can be caused by too many frequent updates of the progress value itself. * With this solution, the UI may only be updated if the current progress is set to the sentinel value. The UI * thread should then update the progress visually and reset the progress value to the sentinel value. Basically, * this behavior is similar to locking. * * <p> * To achieve the latter of the above explanation, this class provides the {@link #getAndSetProgress(double)} method * to get a new value while setting another one with the same call. * </p> * * <blockquote><pre> * <b>Example:</b> * if (progress.getAndSetProgress(newValue) == Progress.SENTINEL) { * Platform.runLater((){@literal ->} { * double value = progress.getAndSetProgress(Progress.SENTINEL); * // perform UI update * }); * } * </pre></blockquote> * * @author Matthias Fussenegger */ public class ProgressManager { /** * Pre-defined sentinel value. */ public static final double SENTINEL = -1d; /** * The total number of operations that are to be tracked. */ private final int _totalOperations; /** * Holds the current progress. */ private final AtomicLong _progress; /** * Maps progress values to identifiers (keys). */ private final ConcurrentMap<Integer, Double> _progressMap = new ConcurrentHashMap<>(); private double calculateProgress(Integer id, double value) { _progressMap.merge(id, value, (oldValue, newValue) -> newValue); double totalProgress = _progressMap.values().stream().mapToDouble(Double::doubleValue).sum(); return totalProgress / _totalOperations / 100d; } /** * Constructs a new instance of this class and initializes the progress with {@link #SENTINEL}. */ public ProgressManager(int totalOperations) { if (totalOperations <= 0) throw new IllegalArgumentException("Total operations must be greater than zero."); _totalOperations = totalOperations; _progress = new AtomicLong(Double.doubleToLongBits(SENTINEL)); } /** * Gets the current value of the progress and sets a new value. * * @param value the value to be set. * @return the previous value. */ public final double getAndSetProgress(double value) { final long newValue = Double.doubleToLongBits(value); final long oldValue = _progress.getAndSet(newValue); return Double.longBitsToDouble(oldValue); } /** * Atomically updates the progress of the specified identifier using the * specified value and also calculates and then returns the total progress * considering all previously added identifiers. If an identifier does not * yet exist it will be created and mapped to the specified id. * * @param id the identifier to be mapped to the progress value. * @param value the updated progress value. * @return the total progress of all stored progress values. */ public double updateProgress(Integer id, double value) { return calculateProgress(id, value); } }
4,282
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Toast.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/Toast.java
/* * Copyright (C) 2020 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.util.Duration; import org.gzipper.java.util.Log; /** * Class for creating and displaying toast messages. * <p> * The implementation of this class is based on <a href="https://stackoverflow.com/a/38373408/8240983">this</a> code. * * @author Matthias Fussenegger */ public final class Toast { private Toast() { throw new AssertionError("Holds static members only"); } /** * Shows a toast using the specified parameters. * * @param ownerStage the owner stage. * @param toastMsg the message to be displayed. * @param msgColor the color of the message. * @param toastDelay specifies how long the toast will be visible. */ public static void show(Stage ownerStage, String toastMsg, Color msgColor, int toastDelay) { show(ownerStage, toastMsg, msgColor, toastDelay, 500, 500); } /** * Shows a toast using the specified parameters. * * @param ownerStage the owner stage. * @param toastMsg the message to be displayed. * @param msgColor the color of the message. * @param toastDelay specifies how long the toast will be visible. * @param fadeInDelay delay when fading in. * @param fadeOutDelay delay when fading out. */ public static void show(Stage ownerStage, String toastMsg, Color msgColor, int toastDelay, int fadeInDelay, int fadeOutDelay) { final Stage toastStage = new Stage(); toastStage.initOwner(ownerStage); toastStage.setResizable(false); toastStage.initStyle(StageStyle.TRANSPARENT); final Text text = new Text(toastMsg); text.setFont(Font.font("Verdana", 28)); text.setFill(msgColor); final StackPane root = new StackPane(text); root.setStyle("-fx-background-radius: 16; " + "-fx-background-color: rgba(0, 0, 0, 0.1); " + "-fx-padding: 32px;"); root.setOpacity(0); final Scene scene = new Scene(root); scene.setFill(Color.TRANSPARENT); double centerXOwnerStage = ownerStage.getX() + ownerStage.getWidth() / 2d; double centerYOwnerStage = ownerStage.getY() + ownerStage.getHeight() / 2d; // size of stage is unknown until rendered, hence hide and relocate toastStage.setOnShowing(windowEvent -> toastStage.hide()); // relocate toast stage to the center of the owner stage toastStage.setOnShown(windowEvent -> { toastStage.setX(centerXOwnerStage - toastStage.getWidth() / 2d); toastStage.setY(centerYOwnerStage - toastStage.getHeight() / 2d); toastStage.show(); }); toastStage.setScene(scene); toastStage.show(); final Timeline fadeInTimeline = new Timeline(); final KeyFrame fadeInKey1 = new KeyFrame(Duration.millis(fadeInDelay), new KeyValue(toastStage.getScene().getRoot().opacityProperty(), 1)); fadeInTimeline.getKeyFrames().add(fadeInKey1); fadeInTimeline.setOnFinished((ev1) -> new Thread(() -> { try { Thread.sleep(toastDelay); } catch (InterruptedException ex) { Log.e("Thread of toast stage interrupted", ex); Thread.currentThread().interrupt(); } final Timeline fadeOutTimeline = new Timeline(); final KeyFrame fadeOutKey1 = new KeyFrame(Duration.millis(fadeOutDelay), new KeyValue(toastStage.getScene().getRoot().opacityProperty(), 0)); fadeOutTimeline.getKeyFrames().add(fadeOutKey1); fadeOutTimeline.setOnFinished((ev2) -> toastStage.close()); fadeOutTimeline.play(); }).start()); fadeInTimeline.play(); } }
4,856
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
GZipper.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/GZipper.java
/* * Copyright (C) 2020 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation; import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.WindowEvent; import org.gzipper.java.application.model.OS; import org.gzipper.java.application.model.OperatingSystem; import org.gzipper.java.application.util.AppUtils; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.presentation.controller.BaseController; import org.gzipper.java.presentation.controller.HashViewController; import org.gzipper.java.presentation.controller.main.MainViewController; import org.gzipper.java.util.Log; import org.gzipper.java.util.Settings; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ResourceBundle; import java.util.logging.*; /** * @author Matthias Fussenegger */ public final class GZipper extends Application { //<editor-fold desc="Constants"> private static final String LAUNCH_MODE_PARAM_NAME = "launch_mode"; private static final String LAUNCH_MODE_APPLICATION = "application"; private static final String LAUNCH_MODE_HASH_VIEW = "hashview"; //</editor-fold> //<editor-fold desc="Initialization"> private void initApplication() { final String decPath = AppUtils.getDecodedRootPath(getClass()); File settings = new File(decPath + "settings.properties"); if (!settings.exists()) { try { // copy settings file to application folder if missing String resource = AppUtils.getResource(GZipper.class, "/settings.properties"); FileUtils.copy(resource, decPath + "settings.properties"); } catch (URISyntaxException | IOException ex) { Log.e(ex.getLocalizedMessage(), ex); } } // determine operating system and initialize settings class OperatingSystem os = System.getProperty("os.name") .toLowerCase().startsWith("windows") ? new OperatingSystem(OS.WINDOWS) : new OperatingSystem(OS.UNIX); Settings.getInstance().init(settings, os); } private void initLogger() { Logger logger = Log.DEFAULT_LOGGER; try { final String decPath = AppUtils.getDecodedRootPath(getClass()); FileHandler handler = new FileHandler(decPath + "gzipper.log"); handler.setFormatter(new SimpleFormatter()); logger.addHandler(handler); Log.setVerboseUiLogging(true); } catch (IOException | SecurityException ex) { logger.log(Level.SEVERE, null, ex); } } //</editor-fold> //<editor-fold desc="Loading of views"> private Parent loadMainView(Stage stage, CSS.Theme theme) throws IOException { var fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/MainView.fxml")); var controller = new MainViewController(theme, getHostServices()); controller.setPrimaryStage(stage); fxmlLoader.setResources(getDefaultResourceBundle()); fxmlLoader.setController(controller); // properly shut down application when closing/hiding window stage.setOnCloseRequest((WindowEvent evt) -> { evt.consume(); controller.getActiveTasks().cancelTasks(); exitApplication(); }); stage.setOnHiding((WindowEvent evt) -> { evt.consume(); controller.getActiveTasks().cancelTasks(); exitApplication(); }); return fxmlLoader.load(); } private Parent loadHashView(Stage stage, CSS.Theme theme) throws IOException { var fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/HashView.fxml")); var controller = new HashViewController(theme); controller.setPrimaryStage(stage); fxmlLoader.setResources(getDefaultResourceBundle()); fxmlLoader.setController(controller); // properly shut down application when closing/hiding window stage.setOnCloseRequest((WindowEvent evt) -> { evt.consume(); controller.interrupt(); exitApplication(); }); stage.setOnHiding((WindowEvent evt) -> { evt.consume(); controller.interrupt(); exitApplication(); }); return fxmlLoader.load(); } //</editor-fold> /** * Returns the default resource bundle to be used by this application. * * @return the default resource bundle to be used by this application. */ private ResourceBundle getDefaultResourceBundle() { return ResourceBundle.getBundle("i18n/gzipper"); } /** * Exits the application gracefully. */ private void exitApplication() { Log.i("Exiting application", false); Platform.exit(); System.exit(0); } @Override public void start(Stage stage) throws Exception { initApplication(); // has to be the first call Settings settings = Settings.getInstance(); final boolean enableLogging = settings.evaluateProperty("loggingEnabled"); final boolean enableDarkTheme = settings.evaluateProperty("darkThemeEnabled"); // initialize logger if logging is enabled if (enableLogging) { initLogger(); } // set correct theme based on settings final CSS.Theme theme = enableDarkTheme ? CSS.Theme.DARK_THEME : CSS.Theme.MODENA; var params = getParameters().getNamed(); // is never null String launchMode = params.get(LAUNCH_MODE_PARAM_NAME); if (launchMode == null) launchMode = LAUNCH_MODE_APPLICATION; Parent parent = switch (launchMode) { case LAUNCH_MODE_APPLICATION -> loadMainView(stage, theme); case LAUNCH_MODE_HASH_VIEW -> loadHashView(stage, theme); default -> throw new IllegalArgumentException(String.format( "Value of parameter '%s' is unknown", LAUNCH_MODE_PARAM_NAME)); }; // load parent to initialize scene Scene scene = new Scene(parent); BaseController.getStages().add(stage); // load CSS theme CSS.load(theme, scene); stage.setTitle("GZipper"); stage.getIcons().add(BaseController.getIconImage()); stage.setScene(scene); stage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { // adjust output of the simple formatter System.setProperty( "java.util.logging.SimpleFormatter.format", "[%1$tm-%1$te-%1$ty, %1$tH:%1$tM:%1$tS] %4$s: %5$s %n" ); // store away settings file at application termination Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { Settings.getInstance().storeAway(); final Logger logger = Log.DEFAULT_LOGGER; for (Handler handler : logger.getHandlers()) { handler.close(); } } catch (IOException ex) { Log.e(ex.getLocalizedMessage(), ex); } })); launch(args); } }
8,041
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
CSS.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/CSS.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation; import javafx.scene.Scene; import org.gzipper.java.util.Log; import java.util.List; /** * Class that allows global access to CSS related information. * * @author Matthias Fussenegger */ public final class CSS { private CSS() { throw new AssertionError("Holds static members only"); } /** * Applies the specified {@link Theme} to the specified {@link Scene}. * <p> * To be more precise, this method clears the list of style sheets of the * specified scene and adds the resource location of the respective CSS file * in external form to the list. This way the alternative theme will be * loaded. * * @param theme the theme to be loaded. * @param scene the scene to which to apply the theme. */ public static void load(Theme theme, Scene scene) { List<String> stylesheets = scene.getStylesheets(); stylesheets.clear(); if (theme != Theme.getDefault()) { var resource = CSS.class.getResource(theme.getLocation()); if (resource != null) { stylesheets.add(resource.toExternalForm()); } else { Log.w("Could not load theme: " + theme.getLocation(), true); } } } /** * Enumeration that consists of all existing visual themes. */ public enum Theme { MODENA("MODENA"), DARK_THEME("/css/DarkTheme.css"); /** * The physical location of the associated style sheet. */ private final String _location; Theme(String location) { _location = location; } /** * Returns the physical location of the associated style sheet. * * @return the physical location of the associated style sheet. */ public String getLocation() { return _location; } /** * Returns the default theme of the application. * * @return the default theme. */ public static Theme getDefault() { return MODENA; } } }
2,849
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Dialogs.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/Dialogs.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Region; import javafx.stage.Stage; import org.gzipper.java.i18n.I18N; import org.gzipper.java.util.Log; import java.util.Optional; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * @author Matthias Fussenegger */ public final class Dialogs { private Dialogs() { throw new AssertionError("Holds static members only"); } /** * Brings up a dialog using the specified parameters. * * @param type the type of the alert. * @param title the title of the dialog. * @param header the header text of the dialog. * @param content the content text of the dialog. * @param theme the CSS theme to be applied. * @param icon the icon to be shown in the title. * @param buttonTypes the buttons to be added. */ public static void showDialog(Alert.AlertType type, String title, String header, String content, CSS.Theme theme, Image icon, ButtonType... buttonTypes) { final Alert alert = new Alert(type, content, buttonTypes); final Stage stage = (Stage) alert.getDialogPane().getScene().getWindow(); stage.getIcons().add(icon); alert.setTitle(title); alert.setHeaderText(header); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); CSS.load(theme, alert.getDialogPane().getScene()); alert.showAndWait(); } /** * Brings up a confirmation dialog using the specified parameters. * * @param title the title of the dialog. * @param header the header text of the dialog. * @param content the content text of the dialog. * @param theme the CSS theme to be applied. * @param icon the icon to be shown in the title. * @return an {@link Optional} to indicate which button has been pressed. */ public static Optional<ButtonType> showConfirmationDialog( String title, String header, String content, CSS.Theme theme, Image icon) { final Alert alert = new Alert(Alert.AlertType.CONFIRMATION, content, ButtonType.YES, ButtonType.NO); final Stage stage = (Stage) alert.getDialogPane().getScene().getWindow(); stage.getIcons().add(icon); alert.setTitle(title); alert.setHeaderText(header); // changing default button to {@code ButtonType.NO} to avoid accidental press of return key Button yesButton = (Button) alert.getDialogPane().lookupButton(ButtonType.YES); Button noButton = (Button) alert.getDialogPane().lookupButton(ButtonType.NO); yesButton.setDefaultButton(false); noButton.setDefaultButton(true); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); CSS.load(theme, alert.getDialogPane().getScene()); return alert.showAndWait(); } /** * Brings up a {@link TextInputDialog} using the specified parameters. * * @param title the title of the dialog. * @param header the header text of the dialog. * @param content the content text of the dialog. * @param theme the CSS theme to be applied. * @param icon the icon to be shown in the title. * @return an {@link Optional} which holds the input text as string. */ public static Optional<String> showTextInputDialog( String title, String header, String content, CSS.Theme theme, Image icon) { final TextInputDialog dialog = new TextInputDialog(); final Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow(); dialog.setTitle(title); dialog.setHeaderText(header); dialog.setContentText(content); stage.getIcons().add(icon); dialog.setResizable(true); dialog.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); CSS.load(theme, dialog.getDialogPane().getScene()); return dialog.showAndWait(); } /** * Brings up a {@link TextInputDialog} which allows the user to enter a * regular expression (pattern). The pattern will also be validated. So if * the returned {@link Optional} holds a result, it is guaranteed that the * result is a valid regular expression. * * @param theme the CSS theme to be applied. * @param icon the icon to be shown in the title. * @return an {@link Optional} which holds the pattern as string. */ public static Optional<String> showPatternInputDialog(CSS.Theme theme, Image icon) { final TextInputDialog dialog = new TextInputDialog(); final Button confirmButton = (Button) dialog .getDialogPane().lookupButton(ButtonType.OK); final Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow(); dialog.setTitle(I18N.getString("applyFilterMenuItem.text")); dialog.setHeaderText(I18N.getString("applyFilterDialogHeader.text")); dialog.setContentText(I18N.getString("applyFilterDialogContent.text")); stage.getIcons().add(icon); dialog.setResizable(true); // key released event to validate regex dialog.getEditor().setOnKeyReleased((KeyEvent event) -> { String text = ((TextField) event.getSource()).getText(); try { // validate regex Pattern.compile(text); confirmButton.setDisable(false); } catch (PatternSyntaxException ex) { Log.w(ex.getMessage(), false); confirmButton.setDisable(true); } }); dialog.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); CSS.load(theme, dialog.getDialogPane().getScene()); return dialog.showAndWait(); } }
6,592
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
GUIUtils.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/GUIUtils.java
/* * Copyright (C) 2020 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation; import javafx.collections.ListChangeListener; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import org.gzipper.java.application.util.AppUtils; import org.gzipper.java.util.Log; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.regex.Pattern; /** * GUI utility class. * * @author Matthias Fussenegger */ public final class GUIUtils { private static final String REGEX_VERSION_LEGACY = "^1\\.\\d"; // e.g. 1.8 private static final Method COLUMN_AUTOFIT_METHOD = initMethod(); private static Method initMethod() { final String methodName = "resizeColumnToFitContent"; final Pattern patternVersionLegacy = Pattern.compile(REGEX_VERSION_LEGACY); Method method = null; try { final Class<?> clazz; final String version = AppUtils.getJavaVersion(); if (patternVersionLegacy.matcher(version).find()) { clazz = Class.forName("com.sun.javafx.scene.control.skin.TableViewSkin"); method = clazz.getDeclaredMethod(methodName, TableColumn.class, int.class); method.setAccessible(true); } /* clazz = Class.forName("javafx.scene.control.skin.TableSkinUtils"); */ // does not work with Java 9 and above since module is not part of public API } catch (ClassNotFoundException | NoSuchMethodException | SecurityException ex) { Log.e("Method lookup via reflection failed", ex); } return method; } private GUIUtils() { throw new AssertionError("Holds static members only"); } /** * Auto fits the columns of the specified table to their content. * * @param table the table of which the columns are to be auto fitted. */ @SuppressWarnings("Convert2Lambda") public static void autoFitTable(TableView<?> table) { if (COLUMN_AUTOFIT_METHOD == null) { return; } table.getItems().addListener(new ListChangeListener<Object>() { @Override public void onChanged(Change<?> c) { table.getColumns().forEach((column) -> { try { if (column.isVisible()) { COLUMN_AUTOFIT_METHOD.invoke(table.getSkin(), column, -1); } } catch (IllegalAccessException | InvocationTargetException ex) { Log.e("Error invoking " + COLUMN_AUTOFIT_METHOD.getName(), ex); } }); } }); } }
3,483
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
TaskGroup.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/TaskGroup.java
/* * Copyright (C) 2022 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import org.gzipper.java.application.util.MapUtils; import org.gzipper.java.util.Log; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Future; /** * Represents a group of tasks (or operations). * * @author Matthias Fussenegger */ public final class TaskGroup { private final ConcurrentMap<Integer, Future<?>> _tasks; private final BooleanProperty _isAnyTasksPresent; /** * Creates a new task group with zero tasks present. */ public TaskGroup() { _tasks = new ConcurrentHashMap<>(); _isAnyTasksPresent = new SimpleBooleanProperty(); } /** * {@code true} if any tasks are present (or known), {@code false} otherwise. */ public BooleanProperty anyTasksPresentProperty() { return _isAnyTasksPresent; } /** * Cancels all currently present (or known) tasks. */ public void cancelTasks() { if (!MapUtils.isNullOrEmpty(_tasks)) { _tasks.keySet().stream().map(_tasks::get) .filter((task) -> (!task.cancel(true))).forEachOrdered((task) -> { // log error message only when cancellation failed Log.e("Task cancellation failed for {0}", task.hashCode()); }); } } /** * Adds the specified task to this group if it is not already present (or known). * * @param id the id of the task to be added. * @param task the task to be added. */ public void put(int id, Future<?> task) { boolean isAdded = _tasks.putIfAbsent(id, task) == null; if (isAdded) { _isAnyTasksPresent.setValue(true); } } /** * Removes the task with the given id from this group. * * @param id the id of the task to remove be removed. */ public void remove(int id) { boolean isRemoved = _tasks.remove(id) != null; if (isRemoved && _tasks.isEmpty()) { _isAnyTasksPresent.setValue(false); } } /** * Returns {@code true} if this group is empty, {@code false} otherwise. * * @return {@code true} if this group is empty, {@code false} otherwise. */ public boolean isEmpty() { return _tasks.isEmpty(); } }
3,167
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
AboutViewController.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/controller/AboutViewController.java
/* * Copyright (C) 2020 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation.controller; import javafx.application.HostServices; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Hyperlink; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.text.*; import org.gzipper.java.application.util.AppUtils; import org.gzipper.java.i18n.I18N; import org.gzipper.java.presentation.CSS; import org.gzipper.java.presentation.GZipper; import org.gzipper.java.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.net.URISyntaxException; import java.net.URL; import java.util.ResourceBundle; /** * Controller for the FXML named "AboutView.fxml". * * @author Matthias Fussenegger */ public final class AboutViewController extends BaseController { /** * The name of the image to be displayed in the about-view. */ private static final String IMG_NAME = "images/icon_256.png"; /** * The name of this application. */ private static final String APP_NAME = "GZipper"; /** * The version of this application. */ private static final String APP_VERSION = "2.2.0"; /** * The build date of this application (mm/dd/yyyy). */ private static final String APP_BUILD_DATE = "03/31/2024"; /** * The author of this application. */ private static final String APP_COPYRIGHT = "Matthias Fussenegger"; /** * The home page of this project. */ private static final String APP_HOME_PAGE = "https://github.com/turbolocust/GZipper"; /** * The image file as a static reference in case it has already been loaded. */ private static File _imageFile; @FXML private ImageView _imageView; @FXML private TextFlow _textFlow; @FXML private Button _closeButton; /** * Constructs a controller for About View with the specified CSS theme and * host services. * * @param theme the {@link CSS} theme to be applied. * @param hostServices the host services to aggregate. */ public AboutViewController(CSS.Theme theme, HostServices hostServices) { super(theme, hostServices); } @FXML void handleCloseButtonAction(ActionEvent evt) { if (evt.getSource().equals(_closeButton)) { close(); } } @Override public void initialize(URL location, ResourceBundle resources) { if (_imageFile == null || !_imageFile.exists()) { String imgRes = null; try { // load image from JAR and display it in image view imgRes = AppUtils.getResource(GZipper.class, "/" + IMG_NAME); } catch (URISyntaxException ex) { Log.e(I18N.getString("error.text"), ex); imgRes = AppUtils.getDecodedRootPath(getClass()) + IMG_NAME; } catch (FileNotFoundException ex) { Log.e(I18N.getString("error.text"), ex); } finally { if (imgRes != null) { _imageFile = new File(imgRes); } } } if (_imageFile != null) { _imageView.setImage(new Image(_imageFile.toURI().toString())); } final Text appName = new Text(APP_NAME + "\n"), appVersion = new Text( "Version" + ": " + APP_VERSION + "\n"), appBuildDate = new Text( resources.getString("buildDate.text") + ": " + APP_BUILD_DATE + "\n"), appCopyright = new Text( resources.getString("author.text") + ": " + APP_COPYRIGHT + "\n\r"), appLicense = new Text( resources.getString("license.text") + "\n\r"); final Hyperlink appHomePage = new Hyperlink(APP_HOME_PAGE); appHomePage.setId("aboutViewAppHomePage"); appHomePage.setOnAction((ActionEvent evt) -> { if (evt.getSource().equals(appHomePage)) { hostServices.showDocument(appHomePage.getText()); } }); // apply different font to app name appName.setFont(Font.font("System", FontWeight.BOLD, 16)); _textFlow.setTextAlignment(TextAlignment.CENTER); _textFlow.getChildren().addAll(appName, appVersion, appBuildDate, appCopyright, appLicense, appHomePage); } }
5,650
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
ViewControllers.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/controller/ViewControllers.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation.controller; import javafx.application.HostServices; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Alert.AlertType; import javafx.scene.image.Image; import javafx.stage.Modality; import javafx.stage.Stage; import org.gzipper.java.i18n.I18N; import org.gzipper.java.presentation.CSS; import org.gzipper.java.presentation.Dialogs; import org.gzipper.java.util.Log; import java.io.IOException; /** * @author Matthias Fussenegger */ public final class ViewControllers { /** * Defines the resource for this view. */ private static final String ABOUT_VIEW_RES = "/fxml/AboutView.fxml"; /** * Defines the resource for the drop view. */ private static final String DROP_VIEW_RES = "/fxml/DropView.fxml"; /** * Defines the resource for the hash view. */ private static final String HASH_VIEW_RES = "/fxml/HashView.fxml"; private ViewControllers() { throw new AssertionError("Holds static members only"); } /** * Shows the about-view in a separate window. * * @param theme the theme to be applied. * @param icon the icon to be used in the view * @param hostServices the host services to be aggregated. */ public static void showAboutView(CSS.Theme theme, Image icon, HostServices hostServices) { if (hostServices == null) { throw new NullPointerException("Host services must not be null"); } final FXMLLoader fxmlLoader = initFXMLLoader(ABOUT_VIEW_RES); AboutViewController controller = new AboutViewController(theme, hostServices); fxmlLoader.setController(controller); final Stage aboutView = new Stage(); aboutView.initModality(Modality.APPLICATION_MODAL); controller.setPrimaryStage(aboutView); try { aboutView.getIcons().add(icon); aboutView.setTitle(I18N.getString("aboutViewTitle.text")); aboutView.setScene(loadScene(fxmlLoader, theme)); aboutView.showAndWait(); } catch (IOException ex) { handleErrorLoadingView(ex, theme, icon); } } /** * Shows the drop view in a separate window. * * @param theme the theme to be applied. * @param icon the icon to be used in the view * @param options used to customize the set-up of the DropView. * @return the controller for the view. */ public static DropViewController showDropView(CSS.Theme theme, Image icon, ViewControllersOptions.DropViewOptions options) { final FXMLLoader fxmlLoader = initFXMLLoader(DROP_VIEW_RES); var controller = new DropViewController(theme, options); fxmlLoader.setController(controller); final Stage dropView = new Stage(); dropView.setAlwaysOnTop(true); dropView.initModality(Modality.APPLICATION_MODAL); controller.setPrimaryStage(dropView); try { dropView.getIcons().add(icon); dropView.setTitle(I18N.getString("addMany.text")); dropView.setScene(loadScene(fxmlLoader, theme)); dropView.showAndWait(); } catch (IOException ex) { handleErrorLoadingView(ex, theme, icon); } return controller; } /** * Shows the hash view in a separate window. * * @param theme the theme to be applied. * @param icon the icon to be used in the view */ public static void showHashView(CSS.Theme theme, Image icon) { final FXMLLoader fxmlLoader = initFXMLLoader(HASH_VIEW_RES); HashViewController controller = new HashViewController(theme); fxmlLoader.setController(controller); final Stage hashView = new Stage(); hashView.setAlwaysOnTop(false); hashView.initModality(Modality.NONE); controller.setPrimaryStage(hashView); // add stage to active stages since window is not modal BaseController.getStages().add(hashView); hashView.setOnCloseRequest(evt -> { Log.i("Closing hash view", false); controller.interrupt(); // cancels any active task }); hashView.setOnHiding(evt -> { Log.i("Hiding hash view", false); controller.interrupt(); // cancels any active task }); try { hashView.getIcons().add(icon); hashView.setTitle(I18N.getString("hashViewTitle.text")); hashView.setScene(loadScene(fxmlLoader, theme)); hashView.show(); } catch (IOException ex) { handleErrorLoadingView(ex, theme, icon); } } /** * Initializes a new {@link FXMLLoader} with the specified resource string * and sets the resources to the default bundle as of {@link I18N}. * * @param resource the resources to initialize the {@link FXMLLoader} with. * @return the initialized {@link FXMLLoader}. */ private static FXMLLoader initFXMLLoader(String resource) { final Class<ViewControllers> clazz = ViewControllers.class; FXMLLoader loader = new FXMLLoader(clazz.getResource(resource)); loader.setResources(I18N.getBundle()); return loader; } /** * Loads a scene by using the specified {@link FXMLLoader} and then applies * the correct theme. * * @param loader the {@link FXMLLoader} to be used. * @param theme the CSS theme to be applied. * @return the loaded {@link Scene}. * @throws IOException if an I/O error occurs. */ private static Scene loadScene(FXMLLoader loader, CSS.Theme theme) throws IOException { Scene scene = new Scene(loader.load()); CSS.load(theme, scene); return scene; } /** * Handles errors that can occur when trying to load a view. This method * will log the localized exception message and bring up an error dialog * using the specified theme. * * @param ex the {@link Exception} to be logged. * @param theme the theme to be applied to the error dialog. * @param icon the icon to be shown in the title. */ private static void handleErrorLoadingView(Exception ex, CSS.Theme theme, Image icon) { Log.e(ex.getLocalizedMessage(), ex); final String errorText = I18N.getString("error.text"); Dialogs.showDialog(AlertType.ERROR, errorText, errorText, I18N.getString("errorOpeningWindow.text"), theme, icon); } }
7,306
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
BaseController.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/controller/BaseController.java
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation.controller; import javafx.application.HostServices; import javafx.application.Platform; import javafx.fxml.Initializable; import javafx.scene.image.Image; import javafx.scene.image.WritableImage; import javafx.stage.Stage; import org.gzipper.java.presentation.CSS; import java.util.HashSet; import java.util.Set; /** * The base controller every other controller should derive from. * * @author Matthias Fussenegger */ public abstract class BaseController implements Initializable { //<editor-fold desc="Static members"> /** * A set with all the stages currently open. */ private static final Set<Stage> _stages = new HashSet<>(); /** * Returns all currently open stages. * * @return all currently open stages. */ public static Set<Stage> getStages() { return _stages; } /** * The icon image to be used by each stage. */ protected static Image iconImage; /** * Returns the icon image that is to be used by each stage. * * @return the icon image that is to be used by each stage. */ public static Image getIconImage() { var resource = BaseController.class.getResource("/images/icon_32.png"); if (resource != null) { iconImage = new Image(resource.toExternalForm()); } else { iconImage = new WritableImage(32, 32); // blank image } return iconImage; } //</editor-fold> /** * The aggregated primary stage. */ protected Stage primaryStage; /** * Sets the primary stage of this controller. * * @param primaryStage the primary stage to be set. */ public void setPrimaryStage(Stage primaryStage) { this.primaryStage = primaryStage; } /** * The aggregated host services. May be {@code null} if not set. */ protected HostServices hostServices; /** * The currently active theme. */ protected CSS.Theme theme; /** * Constructs a controller with the specified CSS theme. * * @param theme the {@link CSS} theme to be applied. */ public BaseController(CSS.Theme theme) { this.theme = theme; } /** * Constructs a controller with the specified CSS theme and host services. * * @param theme the {@link CSS} theme to be applied. * @param hostServices the host services to be aggregated. */ public BaseController(CSS.Theme theme, HostServices hostServices) { this.theme = theme; this.hostServices = hostServices; } /** * Loads the alternative theme (dark theme). * * @param enableTheme true to enable, false to disable the alternative theme. */ protected void loadAlternativeTheme(boolean enableTheme) { this.theme = enableTheme ? CSS.Theme.DARK_THEME : CSS.Theme.getDefault(); _stages.forEach((stage) -> CSS.load(this.theme, stage.getScene())); } /** * Closes the primary stage of this controller. Must be called by the UI thread. */ protected void close() { primaryStage.close(); } /** * Terminates the application gracefully. */ protected void exit() { close(); Platform.exit(); System.exit(0); } }
4,042
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
HashViewController.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/controller/HashViewController.java
/* * Copyright (C) 2020 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation.controller; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.beans.property.SimpleObjectProperty; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.input.*; import javafx.scene.paint.Color; import javafx.stage.FileChooser; import org.gzipper.java.application.concurrency.Interruptible; import org.gzipper.java.application.hashing.MessageDigestAlgorithm; import org.gzipper.java.application.hashing.MessageDigestProvider; import org.gzipper.java.application.hashing.MessageDigestResult; import org.gzipper.java.application.hashing.NamedMessageDigestResult; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.application.util.ListUtils; import org.gzipper.java.application.util.StringUtils; import org.gzipper.java.application.util.TaskHandler; import org.gzipper.java.i18n.I18N; import org.gzipper.java.presentation.CSS; import org.gzipper.java.presentation.Dialogs; import org.gzipper.java.presentation.GUIUtils; import org.gzipper.java.presentation.Toast; import org.gzipper.java.presentation.model.HashViewTableModel; import org.gzipper.java.util.Log; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.security.NoSuchAlgorithmException; import java.util.*; /** * Controller for the FXML named "HashView.fxml". * * @author Matthias Fussenegger */ public final class HashViewController extends BaseController implements Interruptible { /** * Default buffer size when reading large files. Currently, set to 1 mebibyte. */ private static final int BUFFER_SIZE = 1024 * 1024; /** * Threshold at which {@link #BUFFER_SIZE} will be used. Currently, set to 100 Mebibyte. */ private static final int LARGE_FILE_THRESHOLD = 1024 * 1024 * 100; /** * The currently selected {@link MessageDigestAlgorithm}. */ private final ObjectProperty<MessageDigestAlgorithm> _algorithm; /** * Set to remember results for {@link #_resultTable} to avoid duplicates. */ private final Set<NamedMessageDigestResult> _models = new HashSet<>(); /** * Handler used to execute tasks. */ private final TaskHandler _taskHandler; /** * If set to false the currently running task will be interrupted. */ private volatile boolean _isAlive = false; @FXML private TableView<HashViewTableModel> _resultTable; @FXML private TableColumn<HashViewTableModel, String> _fileNameColumn; @FXML private TableColumn<HashViewTableModel, String> _filePathColumn; @FXML private TableColumn<HashViewTableModel, String> _hashValueColumn; @FXML private ComboBox<MessageDigestAlgorithm> _algorithmComboBox; @FXML private Button _addFilesButton; @FXML private Button _closeButton; @FXML private CheckBox _appendFilesCheckBox; @FXML private CheckBox _lowerCaseCheckBox; @FXML private ProgressIndicator _progressIndicator; /** * Constructs a controller for the hash view with the specified CSS theme. * * @param theme the {@link CSS} theme to apply. */ public HashViewController(CSS.Theme theme) { super(theme); _algorithm = new SimpleObjectProperty<>(); _taskHandler = new TaskHandler(TaskHandler.ExecutorType.QUEUED); } @FXML void handleAddFilesButtonAction(ActionEvent evt) { if (evt.getSource().equals(_addFilesButton)) { final FileChooser fc = new FileChooser(); fc.setTitle(I18N.getString("browseForFiles.text")); final List<File> selectedFiles = fc.showOpenMultipleDialog(primaryStage); computeAndAppend(selectedFiles); // performs null check GUIUtils.autoFitTable(_resultTable); } } @FXML void handleLowerCaseCheckBoxAction(ActionEvent evt) { if (evt.getSource().equals(_lowerCaseCheckBox)) { _resultTable.getItems().forEach(item -> item.setHashValue(setCase(item.getHashValue()))); _resultTable.refresh(); } } @FXML void handleAlgorithmComboBoxAction(ActionEvent evt) { if (evt.getSource().equals(_algorithmComboBox)) { final int size = _resultTable.getItems().size(); final List<File> files = new ArrayList<>(size); _resultTable.getItems().stream() .map((model) -> new File(model.getFilePath())) .forEachOrdered(files::add); clearRows(); computeAndAppend(files); GUIUtils.autoFitTable(_resultTable); } } @FXML void handleCloseButtonAction(ActionEvent evt) { if (evt.getSource().equals(_closeButton)) { close(); } } @FXML void handleResultTableOnDragOver(DragEvent evt) { if (evt.getGestureSource() != _resultTable && evt.getDragboard().hasFiles()) { evt.acceptTransferModes(TransferMode.COPY_OR_MOVE); } evt.consume(); } @FXML void handleResultTableOnDragDropped(DragEvent evt) { final Dragboard dragboard = evt.getDragboard(); boolean success = false; if (dragboard.hasFiles()) { computeAndAppend(dragboard.getFiles()); GUIUtils.autoFitTable(_resultTable); success = true; } evt.setDropCompleted(success); evt.consume(); } private void initTableCells() { _fileNameColumn.setCellValueFactory(data -> new ReadOnlyStringWrapper(data.getValue().getFileName())); _filePathColumn.setCellValueFactory(data -> new ReadOnlyStringWrapper(data.getValue().getFilePath())); _hashValueColumn.setCellValueFactory(data -> new ReadOnlyStringWrapper(data.getValue().getHashValue())); setCellFactory(_fileNameColumn); setCellFactory(_filePathColumn); setCellFactory(_hashValueColumn); } private void setCellFactory(TableColumn<HashViewTableModel, String> column) { column.setCellFactory((TableColumn<HashViewTableModel, String> col) -> { final TableCell<HashViewTableModel, String> cell = new TableCell<>() { @Override protected void updateItem(String value, boolean empty) { super.updateItem(value, empty); setText(empty ? null : value); } }; // programmatically set up context menu final ContextMenu ctxMenu = new ContextMenu(); final MenuItem copyMenuItem = new MenuItem(I18N.getString("copy.text")); final MenuItem copyRowMenuItem = new MenuItem(I18N.getString("copyRow.text")); final MenuItem copyAllMenuItem = new MenuItem(I18N.getString("copyAll.text")); final MenuItem compareToMenuItem = new MenuItem(I18N.getString("compareTo.text")); copyMenuItem.setOnAction(evt -> { // copy if (evt.getSource().equals(copyMenuItem)) { final Clipboard clipboard = Clipboard.getSystemClipboard(); final ClipboardContent content = new ClipboardContent(); content.putString(cell.getItem()); clipboard.setContent(content); } }); copyRowMenuItem.setOnAction(evt -> { // copy row if (evt.getSource().equals(copyRowMenuItem)) { final Clipboard clipboard = Clipboard.getSystemClipboard(); final ClipboardContent content = new ClipboardContent(); final StringBuilder sb = new StringBuilder(); final HashViewTableModel model = cell.getTableRow().getItem(); sb.append(model.getFileName()).append("\t") .append(model.getFilePath()).append("\t") .append(model.getHashValue()); content.putString(sb.toString()); clipboard.setContent(content); } }); copyAllMenuItem.setOnAction(evt -> { // copy all if (evt.getSource().equals(copyAllMenuItem)) { final Clipboard clipboard = Clipboard.getSystemClipboard(); final ClipboardContent content = new ClipboardContent(); final StringBuilder sb = new StringBuilder(); _resultTable.getItems().forEach((model) -> sb.append(model.getFileName()).append("\t") .append(model.getFilePath()).append("\t") .append(model.getHashValue()).append("\n")); content.putString(sb.toString()); clipboard.setContent(content); } }); compareToMenuItem.setOnAction(evt -> { // compare to if (evt.getSource().equals(compareToMenuItem)) { final Optional<String> result = Dialogs.showTextInputDialog( I18N.getString("compareTo.text"), I18N.getString("compareToDialogHeader.text"), I18N.getString("hashValue.text"), theme, iconImage); if (result.isPresent() && !result.get().isEmpty()) { final String message; final int delay = 3600; if (result.get().equalsIgnoreCase(cell.getItem())) { message = I18N.getString("equal.text").toUpperCase(); Toast.show(primaryStage, message, Color.GREEN, delay); } else { message = I18N.getString("notEqual.text").toUpperCase(); Toast.show(primaryStage, message, Color.RED, delay); } } } }); ctxMenu.getItems().addAll(copyMenuItem, copyRowMenuItem, copyAllMenuItem, new SeparatorMenuItem(), compareToMenuItem); cell.contextMenuProperty().bind(Bindings .when(cell.emptyProperty()) .then((ContextMenu) null) .otherwise(ctxMenu)); return cell; }); } private String setCase(String value) { return _lowerCaseCheckBox.isSelected() ? value.toLowerCase() : value.toUpperCase(); } /** * Computes the hash value of the specified file and appends the result as a * row to {@link #_resultTable}. * * @param file the file of which to compute and append the hashing result. */ private void computeAndAppend(File file) { try { MessageDigestResult result; if (file.isFile()) { // folders are not supported final MessageDigestAlgorithm algorithm = _algorithm.get(); if (file.length() > LARGE_FILE_THRESHOLD) { final MessageDigestProvider provider = MessageDigestProvider.createProvider(algorithm); try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis, BUFFER_SIZE)) { final byte[] buffer = new byte[BUFFER_SIZE]; int readBytes; while ((readBytes = bis.read(buffer, 0, buffer.length)) > 0) { provider.updateHash(buffer, 0, readBytes); } } result = provider.computeHash(); } else { byte[] bytes = Files.readAllBytes(file.toPath()); result = MessageDigestProvider.computeHash(bytes, algorithm); } final String path = FileUtils.getPath(file); NamedMessageDigestResult namedResult = new NamedMessageDigestResult(result, path); appendColumn(namedResult, file); } } catch (IOException | NoSuchAlgorithmException ex) { Log.e("Error reading file", ex); final MessageDigestResult result = new MessageDigestResult(); appendColumn(new NamedMessageDigestResult(result, StringUtils.EMPTY), file); } } /** * Starts new task if none is already active to compute the hash values for * the specified list of files and to eventually append the results to * {@link #_resultTable}. A task is being used to avoid a non-responsive UI. * * @param files list of files to be processed. */ @SuppressWarnings({"SleepWhileInLoop", "BusyWait"}) private void computeAndAppend(final List<File> files) { if (_isAlive || ListUtils.isNullOrEmpty(files)) { return; } // clear table if append is deactivated if (!_appendFilesCheckBox.isSelected()) { clearRows(); } final Task<Boolean> task = new Task<>() { @Override protected Boolean call() { for (File file : files) { if (!_isAlive) { return false; } computeAndAppend(file); } return true; } }; // set up event handlers task.setOnSucceeded(this::onTaskCompleted); task.setOnFailed(this::onTaskCompleted); bindUIControls(task); _isAlive = true; _taskHandler.submit(task); // wait for task to complete while (task.isRunning()) { try { Thread.sleep(10); } catch (InterruptedException ex) { Log.e("Task interrupted", ex); Thread.currentThread().interrupt(); } } } private void onTaskCompleted(Event evt) { Platform.runLater(this::unbindUIControls); _isAlive = false; evt.consume(); } private void bindUIControls(Task<?> task) { final ReadOnlyBooleanProperty running = task.runningProperty(); _addFilesButton.disableProperty().bind(running); _algorithmComboBox.disableProperty().bind(running); _appendFilesCheckBox.disableProperty().bind(running); _lowerCaseCheckBox.disableProperty().bind(running); _progressIndicator.disableProperty().bind(Bindings.not(running)); _progressIndicator.visibleProperty().bind(running); } private void unbindUIControls() { _addFilesButton.disableProperty().unbind(); _algorithmComboBox.disableProperty().unbind(); _appendFilesCheckBox.disableProperty().unbind(); _lowerCaseCheckBox.disableProperty().unbind(); _progressIndicator.disableProperty().unbind(); _progressIndicator.visibleProperty().unbind(); } /** * Should always be called in favor of {@code table.getItems().clear()} * since this method will also clear the set of added models, which exists * to avoid duplicates in table view. */ private void clearRows() { _resultTable.getItems().clear(); _models.clear(); } private void appendColumn(NamedMessageDigestResult namedResult, File file) { if (!_models.contains(namedResult)) { final HashViewTableModel model; if (!namedResult.getMessageDigestResult().isEmpty()) { model = new HashViewTableModel( file.getName(), FileUtils.getPath(file), setCase(namedResult.getMessageDigestResult().toString())); } else { model = new HashViewTableModel( file.getName(), FileUtils.getPath(file), I18N.getString("errorReadingFile.text")); } Platform.runLater(() -> { _resultTable.getItems().add(model); _models.add(namedResult); }); } } @Override public void initialize(URL location, ResourceBundle resources) { // set up combo box final MessageDigestAlgorithm selectedAlgorithm = MessageDigestAlgorithm.SHA_256; _algorithmComboBox.getItems().addAll(MessageDigestAlgorithm.values()); _algorithmComboBox.valueProperty().bindBidirectional(_algorithm); _algorithm.setValue(selectedAlgorithm); // set up table initTableCells(); final String placeholderText = I18N.getString("addFilesDragDrop.text"); _resultTable.setPlaceholder(new Label(placeholderText)); } @Override public void interrupt() { _isAlive = false; } }
17,958
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
DropViewController.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/controller/DropViewController.java
/* * Copyright (C) 2019 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation.controller; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.TextArea; import javafx.scene.control.Tooltip; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.TransferMode; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.i18n.I18N; import org.gzipper.java.presentation.CSS; import java.net.URL; import java.util.*; /** * Controller for the FXML named "DropView.fxml". * * @author Matthias Fussenegger */ public final class DropViewController extends BaseController { /** * A list consisting of the parsed file addresses. */ private final Set<String> _addresses; /** * Options to customize the set-up of this DropView. */ private final ViewControllersOptions.DropViewOptions _options; @FXML private TextArea _textArea; @FXML private Button _cancelButton; @FXML private Button _submitButton; @FXML private CheckBox _appendAddressesCheckBox; @FXML private CheckBox _putIntoSeparateArchivesCheckBox; @FXML private Text _titleText; /** * Constructs a controller for Drop View with the specified CSS theme. * * @param theme the {@link CSS} theme to be applied. * @param options used to customize the set-up of the DropView. */ public DropViewController(CSS.Theme theme, ViewControllersOptions.DropViewOptions options) { super(theme); _addresses = new LinkedHashSet<>(); _options = options; } @FXML void handleCancelButtonAction(ActionEvent evt) { if (evt.getSource().equals(_cancelButton)) { close(); } } @FXML void handleSubmitButtonAction(ActionEvent evt) { if (evt.getSource().equals(_submitButton)) { final String text = _textArea.getText(); if (!text.isEmpty()) { final var filePathsTokenizer = new StringTokenizer(text, "\"\n"); while (filePathsTokenizer.hasMoreTokens()) { String token = filePathsTokenizer.nextToken(); if (FileUtils.isValid(token)) { _addresses.add(token); } } } close(); } } @FXML void handleTextAreaOnDragOver(DragEvent evt) { if (evt.getGestureSource() != _textArea && evt.getDragboard().hasFiles()) { evt.acceptTransferModes(TransferMode.COPY_OR_MOVE); } evt.consume(); } @FXML void handleTextAreaOnDragDropped(DragEvent evt) { final Dragboard dragboard = evt.getDragboard(); boolean success = false; if (dragboard.hasFiles()) { if (!_appendAddressesCheckBox.isSelected()) { _textArea.clear(); } // add each dropped file's path to text area dragboard.getFiles().forEach((file) -> _textArea.appendText(FileUtils.getPath(file) + "\n")); success = true; } evt.setDropCompleted(success); evt.consume(); } /** * Returns a list of file paths. This list may be empty if no strings have * been parsed or the parsed strings were paths of valid files. * * @return a {@link List} consisting of valid file paths. */ public List<String> getAddresses() { return new LinkedList<>(_addresses); } /** * Returns true if the user wishes to put each file into a separate archive. * * @return true if the user wishes to put each file into a separate archive. */ public boolean isPutInSeparateArchives() { return _putIntoSeparateArchivesCheckBox.isSelected(); } @Override public void initialize(URL location, ResourceBundle resources) { _titleText.setFont(Font.font("System", FontWeight.BOLD, -1)); _appendAddressesCheckBox.setTooltip(new Tooltip(I18N.getString("appendAddressesTooltip.text"))); _putIntoSeparateArchivesCheckBox.setSelected(_options.getPreSelectUiElementsForPuttingFilesIntoSeparateArchives()); _putIntoSeparateArchivesCheckBox.setVisible(!_options.getDisableUiElementsForPuttingFilesIntoSeparateArchives()); } }
5,195
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
CompressState.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/controller/main/CompressState.java
package org.gzipper.java.presentation.controller.main; import org.gzipper.java.application.ArchiveInfo; import org.gzipper.java.application.ArchiveInfoFactory; import org.gzipper.java.application.ArchiveOperation; import org.gzipper.java.application.CompressionMode; import org.gzipper.java.application.model.ArchiveType; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.application.util.ListUtils; import org.gzipper.java.exceptions.GZipperException; import org.gzipper.java.i18n.I18N; import org.gzipper.java.util.Log; import java.io.File; import java.util.ArrayList; import java.util.List; /** * A state which is set when the user wishes to compress files. */ final class CompressState extends ArchivingState { /** * The default archive name of an archive if not explicitly specified. */ static final String DEFAULT_ARCHIVE_NAME = "gzipper_out"; /** * Creates a new instance of {@link CompressState}. * * @param controller the controller to be aggregated. */ CompressState(MainViewController controller) { super(controller); } private String determineOutputPath(File outputFile) { if (!outputFile.exists() || outputFile.isFile()) { return outputFile.getParent(); } return FileUtils.getPath(outputFile); } private List<ArchiveOperation> createArchiveOperationsForEachSelectedFile( List<File> selectedFiles, ArchiveType archiveType) throws GZipperException { List<ArchiveOperation> operations; final List<ArchiveInfo> infos; final String outputPath = determineOutputPath(controller.getOutputFile()); operations = new ArrayList<>(selectedFiles.size()); if (controller.isPutFilesIntoSeparateArchives()) { infos = ArchiveInfoFactory.createArchiveInfos(archiveType, controller.getCompressionLevel(), selectedFiles, outputPath); } else if (selectedFiles.size() == 1) { var info = ArchiveInfoFactory.createArchiveInfo(archiveType, controller.getArchiveName(), controller.getCompressionLevel(), selectedFiles, controller.getOutputFile().getParent()); infos = new ArrayList<>(1); infos.add(info); } else { infos = ArchiveInfoFactory.createArchiveInfos(archiveType, controller.getArchiveName(), controller.getCompressionLevel(), selectedFiles, outputPath); } for (ArchiveInfo info : infos) { var builder = new ArchiveOperation.Builder(info, CompressionMode.COMPRESS); builder.addListener(this).filterPredicate(_filterPredicate); operations.add(builder.build()); } return operations; } @Override public boolean checkUpdateOutputPath() { var selectedFiles = controller.getSelectedFiles(); String outputPath = controller.getTextOfOutputPathTextField(); String extName = controller.getSelectedArchiveType().getDefaultExtensionName(); if (FileUtils.isValidDirectory(outputPath) && !controller.isPutFilesIntoSeparateArchives()) { String archiveName = DEFAULT_ARCHIVE_NAME; if (selectedFiles.size() == 1) { var firstFile = selectedFiles.get(0); archiveName = firstFile.getName(); } // user has not specified output filename outputPath = FileUtils.generateUniqueFilename(outputPath, archiveName, extName); } controller.setArchiveFileExtension(extName); if (FileUtils.isValidOutputFile(outputPath)) { controller.setTextOfOutputPathTextField(outputPath); return true; } return false; } @Override public void performOperations(ArchiveOperation... operations) { if (!ListUtils.isNullOrEmpty(controller.getSelectedFiles())) { super.performOperations(operations); } else { Log.e("Operation(s) cannot be started, because no files have been specified"); Log.i(I18N.getString("noFilesSelectedWarning.text"), true); } } @Override public List<ArchiveOperation> initOperation(ArchiveType archiveType) throws GZipperException { List<ArchiveOperation> operations; var selectedFiles = controller.getSelectedFiles(); if (controller.getSelectedArchiveType() == ArchiveType.GZIP || controller.isPutFilesIntoSeparateArchives()) { operations = createArchiveOperationsForEachSelectedFile(selectedFiles, archiveType); } else { operations = new ArrayList<>(1); var info = ArchiveInfoFactory.createArchiveInfo(archiveType, controller.getArchiveName(), controller.getCompressionLevel(), selectedFiles, controller.getOutputFile().getParent()); var archiveName = info.getArchiveName(); controller.setArchiveName(archiveName); controller.setTextOfOutputPathTextField(FileUtils.combine(info.getOutputPath(), archiveName)); var builder = new ArchiveOperation.Builder(info, CompressionMode.COMPRESS); builder.addListener(this).filterPredicate(_filterPredicate); operations.add(builder.build()); } return operations; } }
5,374
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
ArchivingState.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/controller/main/ArchivingState.java
package org.gzipper.java.presentation.controller.main; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.stage.FileChooser; import javafx.util.converter.PercentageStringConverter; import org.gzipper.java.application.ArchiveInfo; import org.gzipper.java.application.ArchiveOperation; import org.gzipper.java.application.model.ArchiveType; import org.gzipper.java.application.observer.Listener; import org.gzipper.java.application.observer.Notifier; import org.gzipper.java.application.util.StringUtils; import org.gzipper.java.application.util.TaskHandler; import org.gzipper.java.exceptions.GZipperException; import org.gzipper.java.i18n.I18N; import org.gzipper.java.presentation.ProgressManager; import org.gzipper.java.util.Log; import java.util.List; import java.util.concurrent.CancellationException; import java.util.function.Predicate; /** * Represents the currently active state of the {@link MainViewController}. */ abstract class ArchivingState implements Listener<Integer> { /** * The aggregated controller of type {@link MainViewController}. */ protected final MainViewController controller; /** * Handler used to execute tasks. */ private final TaskHandler taskHandler; /** * Converts percentage values to string objects. See method * {@link #update(org.gzipper.java.application.observer.Notifier, java.lang.Integer)}. */ private final PercentageStringConverter _converter = new PercentageStringConverter(); /** * Holds the current progress or {@code -1d}. The current progress is retrieved by the UI thread to update * the progress in the UI. A new task is only submitted to the UI thread if the value is {@code -1d}. * This avoids an unresponsive UI since the UI thread will not be flooded with new tasks. */ private ProgressManager _progressManager; /** * Used to filter files or archive entries when processing archives. */ protected Predicate<String> _filterPredicate = null; /** * Creates a new instance of {@link ArchivingState}. * * @param controller the controller to be aggregated. */ protected ArchivingState(MainViewController controller) { this.controller = controller; taskHandler = new TaskHandler(TaskHandler.ExecutorType.CACHED); } /** * Set the filter to be used when processing archives. * * @param filterPredicate the filter or {@code null} to reset it. */ final void setFilterPredicate(Predicate<String> filterPredicate) { _filterPredicate = filterPredicate; } /** * Returns the filter to be used when processing archives. * * @return the filter to be used when processing archives. If no filter * is set, this method will return {@code null}. */ final Predicate<String> getFilterPredicate() { return _filterPredicate; } /** * Validates the output path specified in user control. * * @return true if output path is valid, false otherwise. */ abstract boolean checkUpdateOutputPath(); /** * Initializes the archiving operation. * * @param archiveType the type of the archive, see {@link ArchiveType}. * @return list consisting of {@link ArchiveOperation}. * @throws GZipperException if the archive type could not have been * determined. */ abstract List<ArchiveOperation> initOperation(ArchiveType archiveType) throws GZipperException; //<editor-fold desc="Private helper methods"> /** * Initializes the archiving job by creating the required {@link Task}. This * task will not perform the algorithmic operations for archiving but instead * constantly checks for interruption to properly detect the abortion of an * operation. For the algorithmic operations a new task will be created and * submitted to the task handler. If an operation has been aborted, e.g. * through user interaction, the operation will be interrupted. * * @param operation the {@link ArchiveOperation} that will eventually be * performed by the task when executed. * @return a {@link Task} that can be executed to perform the specified archiving operation. */ @SuppressWarnings("SleepWhileInLoop") private Task<Boolean> initArchivingJob(final ArchiveOperation operation) { Task<Boolean> task = new Task<>() { @SuppressWarnings("BusyWait") @Override protected Boolean call() throws Exception { final var future = taskHandler.submit(operation); while (!future.isDone()) { try { Thread.sleep(10); // continuous check for interruption } catch (InterruptedException ex) { // if exception is caught, task has been interrupted Log.i(I18N.getString("interrupt.text"), true); Log.w(ex.getLocalizedMessage(), false); operation.interrupt(); if (future.cancel(true)) { Log.i(I18N.getString("operationCancel.text"), true, operation); } } } try { // check for cancellation return future.get(); } catch (CancellationException ex) { return false; // ignore exception } } }; showSuccessMessageAndFinalizeArchivingJob(operation, task); showErrorMessageAndFinalizeArchivingJob(operation, task); return task; } private void showErrorMessageAndFinalizeArchivingJob(ArchiveOperation operation, Task<Boolean> task) { task.setOnFailed(e -> { Log.i(I18N.getString("operationFail.text"), true, operation); final Throwable thrown = e.getSource().getException(); if (thrown != null) Log.e(thrown.getLocalizedMessage(), thrown); finishArchivingJob(operation, task); }); } private void showSuccessMessageAndFinalizeArchivingJob(ArchiveOperation operation, Task<Boolean> task) { task.setOnSucceeded(e -> { final boolean success = (boolean) e.getSource().getValue(); if (success) { Log.i(I18N.getString("operationSuccess.text"), true, operation); } else { Log.w(I18N.getString("operationNoSuccess.text"), true, operation); } finishArchivingJob(operation, task); }); } /** * Calculates the total duration in seconds of the specified {@link ArchiveOperation} * and logs it to the text area. Also toggles the Start and Abort button. * * @param operation {@link ArchiveOperation} that holds elapsed time. * @param task the task to be removed from the list of active tasks. */ private void finishArchivingJob(ArchiveOperation operation, Task<?> task) { Log.i(I18N.getString("elapsedTime.text"), true, operation.calculateElapsedTime()); controller.getActiveTasks().remove(task.hashCode()); if (controller.getActiveTasks().isEmpty()) { controller.enableUIControls(); controller.resetProgressBar(); controller.setTextInProgressBar(StringUtils.EMPTY); } } //</editor-fold> /** * Applies the required extension filters to the specified file chooser. * * @param chooser the {@link FileChooser} to which the extension filters * will be applied to. */ void applyExtensionFilters(FileChooser chooser) { if (chooser != null) { final ArchiveType selectedType = controller.getSelectedArchiveType(); for (ArchiveType type : ArchiveType.values()) { if (type.equals(selectedType)) { FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter( type.getDisplayName(), type.getExtensionNames(true)); chooser.getExtensionFilters().add(extFilter); } } } } /** * Performs the specified array of {@link ArchiveOperation} instances. * * @param operations the {@link ArchiveOperation} instances to be performed. */ void performOperations(ArchiveOperation... operations) { if (operations == null || operations.length == 0) return; _progressManager = new ProgressManager(operations.length); for (var operation : operations) { if (operation != null) { final Task<Boolean> task = initArchivingJob(operation); final ArchiveInfo info = operation.getArchiveInfo(); Log.i(I18N.getString("operationStarted.text"), true, operation, info.getArchiveType().getDisplayName()); Log.i(I18N.getString("outputPath.text", info.getOutputPath()), true); controller.disableUIControlsAsLongAsAnyTaskIsActive(); final var future = taskHandler.submit(task); controller.getActiveTasks().put(task.hashCode(), future); } } } @Override public final void update(Notifier<Integer> notifier, Integer value) { if (value >= 100) { notifier.detach(this); } else { double progress = _progressManager.updateProgress(notifier.getId(), value); if (_progressManager.getAndSetProgress(progress) == ProgressManager.SENTINEL) { Platform.runLater(() -> { double totalProgress = _progressManager.getAndSetProgress(ProgressManager.SENTINEL); if (totalProgress > controller.getProgressOfProgressBar()) { controller.setProgressInProgressBar(totalProgress); controller.setTextInProgressBar(_converter.toString(totalProgress)); } }); } } } }
10,176
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
DecompressState.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/controller/main/DecompressState.java
package org.gzipper.java.presentation.controller.main; import org.gzipper.java.application.ArchiveInfoFactory; import org.gzipper.java.application.ArchiveOperation; import org.gzipper.java.application.CompressionMode; import org.gzipper.java.application.model.ArchiveType; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.application.util.ListUtils; import org.gzipper.java.exceptions.GZipperException; import org.gzipper.java.i18n.I18N; import org.gzipper.java.util.Log; import java.io.File; import java.util.ArrayList; import java.util.List; /** * A state which is set when the user wishes to decompress (or extract) files. */ final class DecompressState extends ArchivingState { /** * Creates a new instance of {@link DecompressState}. * * @param controller the controller to be aggregated. */ DecompressState(MainViewController controller) { super(controller); } private boolean isOutputFileSetAndFilesToBeDecompressedPresent() { return controller.getOutputFile() != null && !ListUtils.isNullOrEmpty(controller.getSelectedFiles()); } @Override public boolean checkUpdateOutputPath() { return FileUtils.isValidDirectory(controller.getTextOfOutputPathTextField()); } @Override public void performOperations(ArchiveOperation... operations) { if (isOutputFileSetAndFilesToBeDecompressedPresent()) { super.performOperations(operations); } else { Log.e("Operation(s) cannot be started, because an invalid path has been specified"); Log.w(I18N.getString("outputPathWarning.text"), true); controller.requestFocusOnOutputPathTextField(); } } @Override public List<ArchiveOperation> initOperation(ArchiveType archiveType) throws GZipperException { var selectedFiles = controller.getSelectedFiles(); List<ArchiveOperation> operations = new ArrayList<>(selectedFiles.size()); for (File file : selectedFiles) { var info = ArchiveInfoFactory.createArchiveInfo(archiveType, FileUtils.getPath(file), FileUtils.getPath(controller.getOutputFile()) + File.separator); var builder = new ArchiveOperation.Builder(info, CompressionMode.DECOMPRESS); builder.addListener(this).filterPredicate(_filterPredicate); operations.add(builder.build()); } return operations; } }
2,470
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
MainViewController.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/controller/main/MainViewController.java
/* * Copyright (C) 2020 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation.controller.main; import javafx.application.HostServices; import javafx.beans.binding.Bindings; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.input.KeyEvent; import javafx.scene.text.Text; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import org.gzipper.java.application.ArchiveOperation; import org.gzipper.java.application.model.ArchiveType; import org.gzipper.java.application.model.OperatingSystem; import org.gzipper.java.application.predicates.PatternPredicate; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.application.util.ListUtils; import org.gzipper.java.exceptions.GZipperException; import org.gzipper.java.i18n.I18N; import org.gzipper.java.presentation.CSS; import org.gzipper.java.presentation.Dialogs; import org.gzipper.java.presentation.TaskGroup; import org.gzipper.java.presentation.controller.BaseController; import org.gzipper.java.presentation.controller.DropViewController; import org.gzipper.java.presentation.controller.ViewControllers; import org.gzipper.java.presentation.controller.ViewControllersOptions; import org.gzipper.java.presentation.handler.TextAreaHandler; import org.gzipper.java.util.Log; import org.gzipper.java.util.Settings; import java.io.File; import java.net.URL; import java.util.*; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.regex.Pattern; import java.util.zip.Deflater; /** * Controller for the FXML named "MainView.fxml". * * @author Matthias Fussenegger */ public final class MainViewController extends BaseController { //<editor-fold desc="Attributes"> /** * Key constant used to access the properties map for menu items. */ private static final String COMPRESSION_LEVEL_KEY = "compressionLevel"; /** * Logger for UI named {@code MainViewController.class.getName()}. */ public static final Logger LOGGER = Logger.getLogger(MainViewController.class.getName()); /** * Holds the currently active tasks (or operations). */ private final TaskGroup activeTasks; public TaskGroup getActiveTasks() { return activeTasks; } /** * The currently active state. */ private ArchivingState _state; /** * The output file or directory that has been selected by the user. */ private File _outputFile; /** * Returns the output file, i.e. the archive or file to be created. * * @return a reference to the output file. */ File getOutputFile() { return _outputFile; } /** * A list consisting of the files that have been selected by the user. * These can either be files to be packed or archives to be extracted. */ private List<File> _selectedFiles; List<File> getSelectedFiles() { return List.copyOf(_selectedFiles); } /** * The archive name specified by the user. */ private String _archiveName; String getArchiveName() { return _archiveName; } void setArchiveName(String archiveName) { _archiveName = archiveName; } /** * The file extension of the archive type. */ private String _archiveFileExtension; void setArchiveFileExtension(String extension) { _archiveFileExtension = extension; } /** * The compression level. Initialized with default compression level. */ private int _compressionLevel; int getCompressionLevel() { return _compressionLevel; } /** * True if user wishes to put each file into a separate archive. */ private boolean _putFilesIntoSeparateArchives; boolean isPutFilesIntoSeparateArchives() { return _putFilesIntoSeparateArchives; } //</editor-fold> //<editor-fold desc="FXML attributes"> @FXML private MenuItem _applyFilterMenuItem; @FXML private MenuItem _resetFilterMenuItem; @FXML private MenuItem _noCompressionMenuItem; @FXML private MenuItem _bestSpeedCompressionMenuItem; @FXML private MenuItem _defaultCompressionMenuItem; @FXML private MenuItem _bestCompressionMenuItem; @FXML private MenuItem _closeMenuItem; @FXML private MenuItem _deleteMenuItem; @FXML private MenuItem _startOperationMenuItem; @FXML private MenuItem _addManyFilesMenuItem; @FXML private MenuItem _addManyFilesSeparateArchiveMenuItem; @FXML private MenuItem _hashingMenuItem; @FXML private MenuItem _resetAppMenuItem; @FXML private MenuItem _aboutMenuItem; @FXML private RadioButton _compressRadioButton; @FXML private RadioButton _decompressRadioButton; @FXML private TextArea _textArea; @FXML private CheckMenuItem _enableLoggingCheckMenuItem; @FXML private CheckMenuItem _enableDarkThemeCheckMenuItem; @FXML private TextField _outputPathTextField; @FXML private ComboBox<ArchiveType> _archiveTypeComboBox; @FXML private Button _startButton; @FXML private Button _abortButton; @FXML private Button _selectFilesButton; @FXML private Button _saveAsButton; @FXML private ProgressBar _progressBar; @FXML private Text _progressText; //</editor-fold> /** * Constructs a controller for Main View with the specified CSS theme and * host services. * * @param theme the {@link CSS} theme to be applied. * @param hostServices the host services to aggregate. */ public MainViewController(CSS.Theme theme, HostServices hostServices) { super(theme, hostServices); _archiveName = CompressState.DEFAULT_ARCHIVE_NAME; _compressionLevel = Deflater.DEFAULT_COMPRESSION; activeTasks = new TaskGroup(); Log.i("Default archive name set to: {0}", _archiveName, false); } //<editor-fold desc="FXML methods"> @FXML void handleApplyFilterMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_applyFilterMenuItem)) { final Optional<String> result = Dialogs.showPatternInputDialog(theme, getIconImage()); if (result.isPresent()) { if (!result.get().isEmpty()) { final Pattern pattern = Pattern.compile(result.get()); _state.setFilterPredicate(new PatternPredicate(pattern)); Log.i(I18N.getString("filterApplied.text", result.get()), true); } else { resetFilter(); } } } } @FXML void handleResetFilterMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_resetFilterMenuItem)) { resetFilter(); } } @FXML void handleCompressionLevelMenuItemAction(ActionEvent evt) { final MenuItem selectedItem = (MenuItem) evt.getSource(); final Object compressionStrength = selectedItem.getProperties().get(COMPRESSION_LEVEL_KEY); if (compressionStrength != null) { _compressionLevel = (int) compressionStrength; final String msg = I18N.getString("compressionLevelChange.text") + " "; Log.i("{0}{1} {2}", true, msg, selectedItem.getText(), "(Deflate)"); } } @FXML void handleCloseMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_closeMenuItem)) { activeTasks.cancelTasks(); exit(); } } @FXML void handleDeleteMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_deleteMenuItem)) { final Optional<ButtonType> result = Dialogs .showConfirmationDialog(I18N.getString("clearText.text"), I18N.getString("clearTextConfirmation.text"), I18N.getString("confirmation.text"), theme, getIconImage()); if (result.isPresent() && result.get() == ButtonType.YES) { _textArea.clear(); _textArea.setText("run:\n"); } } } @FXML void handleStartOperationMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_startOperationMenuItem)) { if (!_startButton.isDisable()) { createAndPerformOperations(); } } } @FXML void handleAddManyFilesMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_addManyFilesMenuItem)) { final boolean preSelectUiElementsForPuttingFilesIntoSeparateArchives = false; final boolean disableUiElementsForPuttingFilesIntoSeparateArchives = _decompressRadioButton.isSelected(); final var options = new ViewControllersOptions.DropViewOptions( preSelectUiElementsForPuttingFilesIntoSeparateArchives, disableUiElementsForPuttingFilesIntoSeparateArchives); final var dropViewController = ViewControllers.showDropView(theme, iconImage, options); performShowDropViewPostAction(dropViewController); } } @FXML void handleAddManyFilesSeparateArchiveMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_addManyFilesSeparateArchiveMenuItem)) { final boolean preSelectUiElementsForPuttingFilesIntoSeparateArchives = true; final boolean disableUiElementsForPuttingFilesIntoSeparateArchives = false; final var options = new ViewControllersOptions.DropViewOptions( preSelectUiElementsForPuttingFilesIntoSeparateArchives, disableUiElementsForPuttingFilesIntoSeparateArchives); final var dropViewController = ViewControllers.showDropView(theme, iconImage, options); performShowDropViewPostAction(dropViewController); } } @FXML void handleHashingMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_hashingMenuItem)) { ViewControllers.showHashView(theme, iconImage); } } @FXML void handleResetAppMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_resetAppMenuItem)) { final Optional<ButtonType> result = Dialogs .showConfirmationDialog(I18N.getString("resetApp.text"), I18N.getString("resetAppConfirmation.text"), I18N.getString("confirmation.text"), theme, getIconImage()); if (result.isPresent() && result.get() == ButtonType.YES) { Settings.getInstance().restoreDefaults(); } } } @FXML void handleAboutMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_aboutMenuItem)) { ViewControllers.showAboutView(theme, iconImage, hostServices); } } @FXML void handleStartButtonAction(ActionEvent evt) { if (evt.getSource().equals(_startButton)) { createAndPerformOperations(); } } @FXML void handleAbortButtonAction(ActionEvent evt) { if (evt.getSource().equals(_abortButton)) { activeTasks.cancelTasks(); } } @FXML void handleSelectFilesButtonAction(ActionEvent evt) { if (evt.getSource().equals(_selectFilesButton)) { final FileChooser fc = new FileChooser(); if (_compressRadioButton.isSelected()) { fc.setTitle(I18N.getString("browseForFiles.text")); } else { fc.setTitle(I18N.getString("browseForArchive.text")); _state.applyExtensionFilters(fc); } final List<File> selectedFiles = fc.showOpenMultipleDialog(primaryStage); String message; if (selectedFiles != null) { _putFilesIntoSeparateArchives = false; _startButton.setDisable(false); int size = selectedFiles.size(); message = I18N.getString("filesSelected.text", size); if (size <= 10) { selectedFiles.forEach((file) -> { // log the path of each selected file Log.i("{0}: \"{1}\"", true, I18N.getString("fileSelected.text"), FileUtils.getPath(file)); }); } _selectedFiles = selectedFiles; } else { message = I18N.getString("noFilesSelected.text"); _startButton.setDisable(ListUtils.isNullOrEmpty(_selectedFiles)); } Log.i(message, true); } } @FXML void handleSaveAsButtonAction(ActionEvent evt) { if (evt.getSource().equals(_saveAsButton)) { final File file = pickFileToBeSaved(); if (file != null) { updateSelectedFile(file); String path = FileUtils.getPath(file); if (!file.isDirectory() && FileUtils.getExtension(path).isEmpty()) { path += _archiveFileExtension; } setOutputPath(path); Log.i("Output file set to: {0}", FileUtils.getPath(file), false); } } } @FXML void handleModeRadioButtonAction(ActionEvent evt) { if (evt.getSource().equals(_compressRadioButton)) { performModeRadioButtonAction(true, "browseForFiles.text", "saveAsArchive.text"); } else if (evt.getSource().equals(_decompressRadioButton)) { performModeRadioButtonAction(false, "browseForArchive.text", "saveAsFiles.text"); } resetSelectedFiles(); } @FXML void handleArchiveTypeComboBoxAction(ActionEvent evt) { if (evt.getSource().equals(_archiveTypeComboBox)) { var archiveType = _archiveTypeComboBox.getValue(); Log.i("Archive type selection change to: {0}", archiveType, false); if (archiveType == ArchiveType.GZIP) { performGzipSelectionAction(); } if (_decompressRadioButton.isSelected()) { resetSelectedFiles(); } else { // update file extension final String outputPathText = _outputPathTextField.getText(); final String fileExtension = archiveType.getDefaultExtensionName(); String outputPath; if (outputPathText.endsWith(_archiveFileExtension)) { int lastIndexOfExtension = outputPathText.lastIndexOf(_archiveFileExtension); outputPath = outputPathText.substring(0, lastIndexOfExtension) + fileExtension; } else if (!FileUtils.isValidDirectory(outputPathText)) { outputPath = outputPathText + fileExtension; } else { outputPath = outputPathText; } setOutputPath(outputPath); _archiveFileExtension = fileExtension; } } } @FXML void handleOutputPathTextFieldKeyTyped(KeyEvent evt) { if (evt.getSource().equals(_outputPathTextField)) { String filename = _outputPathTextField.getText(); if (!FileUtils.containsIllegalChars(filename)) { updateSelectedFile(new File(filename)); } } } @FXML void handleEnableLoggingCheckMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_enableLoggingCheckMenuItem)) { boolean enableLogging = _enableLoggingCheckMenuItem.isSelected(); Settings.getInstance().setProperty("loggingEnabled", enableLogging); Log.setVerboseUiLogging(enableLogging); } } @FXML void handleEnableDarkThemeCheckMenuItemAction(ActionEvent evt) { if (evt.getSource().equals(_enableDarkThemeCheckMenuItem)) { boolean enableTheme = _enableDarkThemeCheckMenuItem.isSelected(); loadAlternativeTheme(enableTheme); Settings.getInstance().setProperty("darkThemeEnabled", enableTheme); } } //</editor-fold> //<editor-fold desc="Methods related to UI"> private void checkUpdateOutputFileAndArchiveName(String outputPath) { if (!FileUtils.getPath(_outputFile).equals(outputPath)) { _outputFile = new File(outputPath); if (!_outputFile.isDirectory()) { _archiveName = _outputFile.getName(); } } } private File pickFileToBeSaved() { final File file; if (_compressRadioButton.isSelected() && _putFilesIntoSeparateArchives) { var directoryChooser = new DirectoryChooser(); directoryChooser.setTitle(I18N.getString("saveAsArchiveTitle.text")); file = directoryChooser.showDialog(primaryStage); } else if (_compressRadioButton.isSelected()) { var fileChooser = new FileChooser(); fileChooser.setTitle(I18N.getString("saveAsArchiveTitle.text")); _state.applyExtensionFilters(fileChooser); file = fileChooser.showSaveDialog(primaryStage); } else { var directoryChooser = new DirectoryChooser(); directoryChooser.setTitle(I18N.getString("saveAsPathTitle.text")); file = directoryChooser.showDialog(primaryStage); } return file; } private void performModeRadioButtonAction(boolean compress, String selectFilesButtonText, String saveAsButtonText) { _state = compress ? new CompressState(this) : new DecompressState(this); _addManyFilesSeparateArchiveMenuItem.setDisable(!compress); _selectFilesButton.setText(I18N.getString(selectFilesButtonText)); _saveAsButton.setText(I18N.getString(saveAsButtonText)); } private void performGzipSelectionAction() { final Settings settings = Settings.getInstance(); final String propertyKey = "showGzipInfoDialog"; final boolean showDialog = settings.evaluateProperty(propertyKey); if (showDialog) { final String infoTitle = I18N.getString("info.text"); final String infoText = I18N.getString("gzipCompressionInfo.text", ArchiveType.TAR_GZ.getDisplayName()); Dialogs.showDialog(Alert.AlertType.INFORMATION, infoTitle, infoTitle, infoText, theme, getIconImage()); settings.setProperty(propertyKey, false); } } private void performShowDropViewPostAction(DropViewController dropViewController) { final var filePaths = dropViewController.getAddresses(); if (!ListUtils.isNullOrEmpty(filePaths)) { _putFilesIntoSeparateArchives = dropViewController.isPutInSeparateArchives(); final int size = filePaths.size(); _selectedFiles = new ArrayList<>(size); _startButton.setDisable(false); if (size > 10) { // threshold, to avoid flooding text area filePaths.forEach((filePath) -> _selectedFiles.add(new File(filePath))); Log.i(I18N.getString("manyFilesSelected.text"), true, size); } else { // log files in detail filePaths.stream() .peek((filePath) -> _selectedFiles.add(new File(filePath))) .forEachOrdered((filePath) -> Log.i("{0}: {1}", true, I18N.getString("fileSelected.text"), filePath)); } } else { Log.i(I18N.getString("noFilesSelected.text"), true); _startButton.setDisable(ListUtils.isNullOrEmpty(_selectedFiles)); } } private void resetFilter() { final boolean wasApplied = _state.getFilterPredicate() != null; _state.setFilterPredicate(null); if (wasApplied) { Log.i(I18N.getString("filterReset.text"), true); } } private void resetSelectedFiles() { if (!ListUtils.isNullOrEmpty(_selectedFiles)) { Log.i(I18N.getString("selectionReset.text"), true); } _putFilesIntoSeparateArchives = false; _selectedFiles = Collections.emptyList(); _startButton.setDisable(true); } private void setOutputPath(String outputPath) { String osStyleFilePath = outputPath.replace('/', File.separatorChar); _outputPathTextField.setText(osStyleFilePath); } private void updateSelectedFile(File file) { if (file != null) { if (!file.isDirectory()) { final String archiveName = _archiveName = file.getName(); String fileExtension = FileUtils.getExtension(archiveName, true); if (fileExtension.isEmpty()) { fileExtension = _archiveTypeComboBox.getValue().getDefaultExtensionName(); } _archiveFileExtension = fileExtension; } _outputFile = file; } } /** * Disables all relevant UI controls as long as any task is active (or running). * Once disabled, a UI control is unusable (or greyed-out). */ void disableUIControlsAsLongAsAnyTaskIsActive() { if (_startButton.disableProperty().isBound()) return; final var runningProperty = activeTasks.anyTasksPresentProperty(); _startButton.disableProperty().bind(runningProperty); _abortButton.disableProperty().bind(Bindings.not(runningProperty)); _compressRadioButton.disableProperty().bind(runningProperty); _decompressRadioButton.disableProperty().bind(runningProperty); _archiveTypeComboBox.disableProperty().bind(runningProperty); _saveAsButton.disableProperty().bind(runningProperty); _selectFilesButton.disableProperty().bind(runningProperty); _addManyFilesMenuItem.disableProperty().bind(runningProperty); _progressBar.visibleProperty().bind(runningProperty); _progressText.visibleProperty().bind(runningProperty); _addManyFilesSeparateArchiveMenuItem.setDisable(true); } /** * Enables all relevant UI controls, i.e. makes them usable again. */ void enableUIControls() { _startButton.disableProperty().unbind(); _abortButton.disableProperty().unbind(); _compressRadioButton.disableProperty().unbind(); _decompressRadioButton.disableProperty().unbind(); _archiveTypeComboBox.disableProperty().unbind(); _selectFilesButton.disableProperty().unbind(); _saveAsButton.disableProperty().unbind(); _addManyFilesMenuItem.disableProperty().unbind(); _addManyFilesSeparateArchiveMenuItem.disableProperty().unbind(); _addManyFilesSeparateArchiveMenuItem.setDisable(_decompressRadioButton.isSelected()); _progressBar.visibleProperty().unbind(); _progressText.visibleProperty().unbind(); } /** * Returns archive type, which is currently selected by the user. * * @return the currently selected archive type. */ ArchiveType getSelectedArchiveType() { return _archiveTypeComboBox.getSelectionModel().getSelectedItem(); } /** * Returns the text currently set in the text field which specifies the output path. * * @return the text currently set in the text field which specifies the output path. */ String getTextOfOutputPathTextField() { return _outputPathTextField.getText(); } /** * Sets the specified {@code text} in the text field which specifies the output path. * * @param text the text to be set in the text field which specifies the output path. */ void setTextOfOutputPathTextField(String text) { _outputPathTextField.setText(text); } /** * Returns the currently set progress of the progress bar. * * @return the currently set progress of the progress bar. */ double getProgressOfProgressBar() { return _progressBar.getProgress(); } /** * Sets the current progress of the progress bar (from 0 to 1). * * @param value the progress of the progress bar to be set. */ void setProgressInProgressBar(double value) { _progressBar.setProgress(value); } /** * Requests the focus on the text field which specifies the output path. */ void requestFocusOnOutputPathTextField() { _outputPathTextField.requestFocus(); } /** * Resets the progress of the progress bar. */ void resetProgressBar() { setProgressInProgressBar(0d); } /** * Sets the text visible in the progress bar. * * @param text the text visible in the progress bar. */ void setTextInProgressBar(String text) { _progressText.setText(text); } //</editor-fold> private void createAndPerformOperations() { try { if (_state.checkUpdateOutputPath()) { final String outputPathText = _outputPathTextField.getText(); final File outputFile = new File(outputPathText); final String outputPath = FileUtils.getPath(outputFile); checkUpdateOutputFileAndArchiveName(outputPath); final String recentPath = FileUtils.getParent(outputPath); Settings.getInstance().setProperty("recentPath", recentPath); final var archiveType = _archiveTypeComboBox.getValue(); final var operations = _state.initOperation(archiveType); for (var operation : operations) { Log.i("Starting operation using the following archive info: {0}", operation.getArchiveInfo().toString(), false); } _state.performOperations(operations.toArray(new ArchiveOperation[0])); } else { Log.w(I18N.getString("invalidOutputPath.text"), true); } } catch (GZipperException ex) { Log.e(ex.getLocalizedMessage(), ex); } } //<editor-fold desc="Initialization"> private void initLogger() { TextAreaHandler handler = new TextAreaHandler(_textArea); handler.setFormatter(new SimpleFormatter()); Log.setLoggerForUI(LOGGER.getName()); LOGGER.setUseParentHandlers(false); LOGGER.addHandler(handler); } @Override public void initialize(URL location, ResourceBundle resources) { initLogger(); final Settings settings = Settings.getInstance(); setRecentlyUsedPathInOutputPathTextField(settings); if (theme == CSS.Theme.DARK_THEME) { _enableDarkThemeCheckMenuItem.setSelected(true); } setUpPropertiesForCompressionLevelMenuItem(); setUpArchiveTypesComboBox(); final boolean enableLogging = settings.evaluateProperty("loggingEnabled"); _enableLoggingCheckMenuItem.setSelected(enableLogging); _state = new CompressState(this); // the default one final String formattedText = String.format("run:\n%s\n", I18N.getString("changeOutputPath.text")); _textArea.setText(formattedText); } private void setRecentlyUsedPathInOutputPathTextField(Settings settings) { final OperatingSystem os = settings.getOs(); final String recentPath = settings.getProperty("recentPath"); if (FileUtils.isValidDirectory(recentPath)) { setOutputPath(recentPath); } else { setOutputPath(os.getDefaultUserDirectory()); } _outputFile = new File(_outputPathTextField.getText()); } private void setUpArchiveTypesComboBox() { final ArchiveType selectedType = ArchiveType.TAR_GZ; _archiveTypeComboBox.getItems().addAll(ArchiveType.values()); _archiveTypeComboBox.setValue(selectedType); _archiveFileExtension = selectedType.getDefaultExtensionName(); } private void setUpPropertiesForCompressionLevelMenuItem() { _noCompressionMenuItem.getProperties().put(COMPRESSION_LEVEL_KEY, Deflater.NO_COMPRESSION); _bestSpeedCompressionMenuItem.getProperties().put(COMPRESSION_LEVEL_KEY, Deflater.BEST_SPEED); _defaultCompressionMenuItem.getProperties().put(COMPRESSION_LEVEL_KEY, Deflater.DEFAULT_COMPRESSION); _bestCompressionMenuItem.getProperties().put(COMPRESSION_LEVEL_KEY, Deflater.BEST_COMPRESSION); } //</editor-fold> }
29,215
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
TextAreaHandler.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/handler/TextAreaHandler.java
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation.handler; import javafx.application.Platform; import javafx.scene.control.TextArea; import java.util.logging.LogRecord; import java.util.logging.StreamHandler; /** * Handles the logging of information to text areas. An instance of this class * requires the aggregation of an {@link TextArea} and derives from * {@link StreamHandler}. This makes logging of information using the Java * logging API much easier as this instance can be used as a handler for logs. * * @author Matthias Fussenegger */ public class TextAreaHandler extends StreamHandler { private final TextArea _textArea; /** * Constructs a new handler for displaying log messages in a text area. * * @param textArea the text area which will display the log messages. */ public TextAreaHandler(TextArea textArea) { _textArea = textArea; } @Override public void publish(LogRecord record) { super.publish(record); flush(); if (_textArea != null) { Platform.runLater(() -> _textArea.appendText(getFormatter().format(record))); } } }
1,840
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
HashViewTableModel.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/presentation/model/HashViewTableModel.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation.model; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.beans.property.SimpleStringProperty; /** * @author Matthias Fussenegger */ public final class HashViewTableModel { private final ReadOnlyStringWrapper _fileName; private final ReadOnlyStringWrapper _filePath; private final ReadOnlyStringWrapper _hashValue; private final SimpleStringProperty _hashValueProperty; public HashViewTableModel(String fileName, String filePath, String hashValue) { _fileName = new ReadOnlyStringWrapper(fileName); _filePath = new ReadOnlyStringWrapper(filePath); _hashValue = new ReadOnlyStringWrapper(); // bind read/write property to allow update of hash value // e.g. in case of lower case conversion triggered in UI _hashValueProperty = new SimpleStringProperty(hashValue); _hashValue.bind(_hashValueProperty); } public String getFileName() { return _fileName.get(); } public String getFilePath() { return _filePath.get(); } public String getHashValue() { return _hashValue.get(); } public void setHashValue(String value) { _hashValueProperty.setValue(value); } public ReadOnlyStringWrapper fileNameProperty() { return _fileName; } public ReadOnlyStringWrapper filePathProperty() { return _filePath; } public ReadOnlyStringWrapper hashValueProperty() { return _hashValue; } @Override public String toString() { return "HashViewTableModel{" + "_fileName=" + _fileName + ", _filePath=" + _filePath + ", _hashValue=" + _hashValue + '}'; } }
2,452
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
CompressionMode.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/CompressionMode.java
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application; /** * Enumeration type for compression modes. * * @author Matthias Fussenegger */ public enum CompressionMode { COMPRESS, DECOMPRESS }
905
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
ArchiveOperation.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/ArchiveOperation.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.compressors.CompressorException; import org.gzipper.java.application.algorithm.CompressionAlgorithm; import org.gzipper.java.application.concurrency.Interruptible; import org.gzipper.java.application.observer.Listener; import org.gzipper.java.exceptions.GZipperException; import org.gzipper.java.i18n.I18N; import org.gzipper.java.util.Log; import java.io.IOException; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Predicate; /** * Object that represents an archiving operation. * * @author Matthias Fussenegger */ public final class ArchiveOperation implements Callable<Boolean>, Interruptible { /** * The aggregated {@link ArchiveInfo}. */ private final ArchiveInfo _archiveInfo; /** * The algorithm that is used for either creating or extracting an archive. * It will be determined during the initialization of an object. */ private final CompressionAlgorithm _algorithm; /** * Describes what kind of operation shall be performed. */ private final CompressionMode _compressionMode; /** * The elapsed time of the operation which will be stored after its end. */ private final AtomicLong _elapsedTime = new AtomicLong(); /** * The start time of this operation. */ private long _startTime = 0L; /** * True if a request for interruption has been received. */ private volatile boolean _interrupt = false; /** * True if operation is completed, false otherwise. */ private volatile boolean _completed = false; private ArchiveOperation(final ArchiveOperation.Builder builder) { _archiveInfo = builder._archiveInfo; _algorithm = builder._algorithm; _compressionMode = builder._compressionMode; _algorithm.setPredicate(builder._filterPredicate); } private void setElapsedTime() { if (_elapsedTime.get() == 0) { _elapsedTime.set(System.nanoTime() - _startTime); } } private void performOperation() throws IOException, ArchiveException, CompressorException, GZipperException { Log.i(I18N.getString("processingArchiveFile.text"), _archiveInfo.getArchiveName(), true); switch (_compressionMode) { case COMPRESS -> _algorithm.compress(_archiveInfo); case DECOMPRESS -> _algorithm.extract(_archiveInfo); default -> throw GZipperException.createWithReason( GZipperException.Reason.ILLEGAL_MODE, "Mode could not be determined"); } } /** * Calculates the elapsed time in seconds. * * @return the elapsed time in seconds. */ public double calculateElapsedTime() { return _startTime > 0L ? (_elapsedTime.doubleValue() / 1E9) : 0d; } /** * Returns the aggregated instance of {@link ArchiveInfo}. * * @return the aggregated instance of {@link ArchiveInfo}. */ public ArchiveInfo getArchiveInfo() { return _archiveInfo; } /** * Returns true if this operation is completed, false otherwise. * * @return true if this operation is completed, false otherwise. */ public boolean isCompleted() { return _completed; } @Override public Boolean call() throws Exception { if (isCompleted()) throw new IllegalStateException("Operation already completed"); boolean success = false; _startTime = System.nanoTime(); try { performOperation(); success = true; } catch (IOException ex) { if (!_interrupt) { final Throwable cause = ex.getCause(); if (cause instanceof GZipperException inner) { if (inner.getReason() == GZipperException.Reason.NO_DIR_SUPPORTED) { Log.w(I18N.getString("noDirSupported.text"), true); } } Log.e(ex.getLocalizedMessage(), ex); Log.w(I18N.getString("corruptArchive.text"), true); } } catch (CompressorException | ArchiveException ex) { Log.e(ex.getLocalizedMessage(), ex); Log.w(I18N.getString("wrongFormat.text"), true); } finally { setElapsedTime(); _completed = true; _algorithm.clearListeners(); } return success; } @Override public void interrupt() { if (!isCompleted()) { _interrupt = true; _algorithm.clearListeners(); _algorithm.interrupt(); setElapsedTime(); // eliminates race condition } } @Override public String toString() { return Integer.toString(hashCode()); } /** * Builder class for {@link ArchiveOperation}. */ public static class Builder { // required parameters private final ArchiveInfo _archiveInfo; private final CompressionAlgorithm _algorithm; private final CompressionMode _compressionMode; // optional parameters private Predicate<String> _filterPredicate = null; /** * Constructs a new instance of this class using the specified values. * * @param info the {@link ArchiveInfo} to be aggregated. * @param compressionMode the {@link CompressionMode} for this * operation. * @throws org.gzipper.java.exceptions.GZipperException if determination * of archiving algorithm has failed. */ public Builder(ArchiveInfo info, CompressionMode compressionMode) throws GZipperException { // check parameters first Objects.requireNonNull(info); Objects.requireNonNull(compressionMode); // set fields and initialize algorithm _archiveInfo = info; _compressionMode = compressionMode; if ((_algorithm = init(info)) == null) { throw new GZipperException(new NullPointerException("Algorithm could not be determined")); } } private CompressionAlgorithm init(ArchiveInfo info) { return info.getArchiveType().getAlgorithm(); } /** * Sets the predicate to be used by the operation. * * @param predicate the {@link Predicate} to be used. * @return a reference to this to allow method chaining. */ @SuppressWarnings("UnusedReturnValue") public final Builder filterPredicate(Predicate<String> predicate) { _filterPredicate = predicate; return this; } /** * Attaches a new listener to the algorithm instance of the operation. * * @param listener listener to be attached to this algorithm instance. * @return a reference to this to allow method chaining. */ public final Builder addListener(Listener<Integer> listener) { _algorithm.attach(listener); return this; } /** * Builds a new instance of {@link ArchiveOperation}. * * @return a new instance of {@link ArchiveOperation}. */ public final ArchiveOperation build() { return new ArchiveOperation(this); } } }
8,379
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
ArchiveInfoFactory.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/ArchiveInfoFactory.java
/* * Copyright (C) 2019 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application; import org.gzipper.java.application.model.ArchiveType; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.exceptions.GZipperException; import java.io.File; import java.util.*; import java.util.zip.Deflater; /** * Factory class that offers static methods for creating {@link ArchiveInfo}. * * @author Matthias Fussenegger */ public final class ArchiveInfoFactory { private ArchiveInfoFactory() { throw new AssertionError("Holds static members only"); } /** * Creates a new {@link ArchiveInfo} for a compression operation. * * @param archiveType the type of the archive, see {@link ArchiveType}. * @param archiveName the name of the archive to be created. * @param level the compression level of the archive. * @param files the files to be compressed. * @param outputPath the path where to save the archive. * @return a new {@link ArchiveInfo} object. * @throws GZipperException if archive type could not be determined. */ public static ArchiveInfo createArchiveInfo( ArchiveType archiveType, String archiveName, int level, List<File> files, String outputPath) throws GZipperException { if (archiveType == null) { throw new NullPointerException("Archive type must not be null"); } else throwGZipperExceptionIfFaultyCompressionLevelSpecified(level); final String properName = checkAddExtension(archiveName, archiveType); final String ext = FileUtils.getExtension(properName, true); final int lastIndexOfExtension = properName.lastIndexOf(ext); final String displayName = properName.substring(0, lastIndexOfExtension); final String fullName = FileUtils.generateUniqueFilename(outputPath, displayName, ext, 0); String name = FileUtils.getName(fullName); return new ArchiveInfo(archiveType, name, level, files, outputPath); } /** * Creates a new {@link ArchiveInfo} for a compression operation. This will generate a unique archive name * for each file provided, using the specified archive name so that each file starts with the same name and * ends with a unique identifier (or number) starting from one ({@code 1}). * * @param archiveType the type of the archive, see {@link ArchiveType}. * @param archiveName the name of the archive to be created. * @param level the compression level of the archive. * @param files the files to be compressed. * @param outputPath the path where to save the archive. * @return a list consisting of {@link ArchiveInfo} objects. * @throws GZipperException if archive type could not be determined. */ public static List<ArchiveInfo> createArchiveInfos( ArchiveType archiveType, String archiveName, int level, List<File> files, String outputPath) throws GZipperException { if (archiveType == null) { throw new NullPointerException("Archive type must not be null"); } throwGZipperExceptionIfFaultyCompressionLevelSpecified(level); final String properName = checkAddExtension(archiveName, archiveType); final String ext = FileUtils.getExtension(properName, true); final int lastIndexOfExtension = properName.lastIndexOf(ext); final String displayName = properName.substring(0, lastIndexOfExtension); final Set<String> names = new HashSet<>(); // to avoid name collisions List<ArchiveInfo> archiveInfos = new ArrayList<>(files.size()); String fullName, name; // hold the names of the (next) archive int nameSuffix = 0; // will be appended if necessary for (File nextFile : files) { List<File> fileList = new LinkedList<>(); fileList.add(nextFile); do { ++nameSuffix; fullName = displayName + nameSuffix; fullName = FileUtils.generateUniqueFilename(outputPath, fullName, ext, nameSuffix); name = FileUtils.getName(fullName); } while (names.contains(name)); names.add(name); ArchiveInfo info = new ArchiveInfo(archiveType, name, level, fileList, outputPath); archiveInfos.add(info); } return archiveInfos; } /** * Creates a new {@link ArchiveInfo} for a compression operation. This will generate a unique archive name * for each file provided if it already exists, so that the file ends with a unique identifier (or number). * * @param archiveType the type of the archive, see {@link ArchiveType}. * @param level the compression level of the archive. * @param files the files to be compressed. * @param outputPath the path where to save the archive. * @return a list consisting of {@link ArchiveInfo} objects. * @throws GZipperException if archive type could not be determined. */ public static List<ArchiveInfo> createArchiveInfos(ArchiveType archiveType, int level, List<File> files, String outputPath) throws GZipperException { if (archiveType == null) { throw new NullPointerException("Archive type must not be null"); } throwGZipperExceptionIfFaultyCompressionLevelSpecified(level); final String ext = archiveType.getDefaultExtensionName(); final int nameSuffix = 1; // will be appended if necessary List<ArchiveInfo> archiveInfos = new ArrayList<>(files.size()); for (File nextFile : files) { List<File> fileList = new LinkedList<>(); fileList.add(nextFile); String fullName = FileUtils.generateUniqueFilename(outputPath, nextFile.getName(), ext, nameSuffix); String name = FileUtils.getName(fullName); ArchiveInfo info = new ArchiveInfo(archiveType, name, level, fileList, outputPath); archiveInfos.add(info); } return archiveInfos; } /** * Creates a new {@link ArchiveInfo} for a decompression operation. * * @param archiveType the type of the archive, see {@link ArchiveType}. * @param archiveName the name of the archive to be extracted. * @param outputPath the path where to extract the archive. * @return {@link ArchiveInfo} that may be used for an operation. */ public static ArchiveInfo createArchiveInfo(ArchiveType archiveType, String archiveName, String outputPath) { if (archiveType == null) { throw new NullPointerException("Archive type must not be null"); } return new ArchiveInfo(archiveType, archiveName, 0, null, outputPath); } private static String checkAddExtension(String archiveName, ArchiveType archiveType) { String name = archiveName; boolean hasExtension = false; final String[] extNames = archiveType.getExtensionNames(false); for (String extName : extNames) { if (archiveName.endsWith(extName)) { hasExtension = true; break; } } if (!hasExtension) { name = archiveName + extNames[0]; // add extension to archive name if missing and ignore the asterisk } return name; } private static void throwGZipperExceptionIfFaultyCompressionLevelSpecified(int level) throws GZipperException { if (level < Deflater.DEFAULT_COMPRESSION || level > Deflater.BEST_COMPRESSION) { throw GZipperException.createWithReason( GZipperException.Reason.FAULTY_COMPRESSION_LVL, "Faulty compression level specified"); } } }
8,520
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
MessageDigestResult.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/hashing/MessageDigestResult.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.hashing; import org.gzipper.java.application.util.StringUtils; import java.util.Arrays; import java.util.Objects; /** * Holds result values of message digest algorithms. * * @author Matthias Fussenegger */ public final class MessageDigestResult { private final byte[] _hashedBytes; private final String _hashedValue; public MessageDigestResult() { _hashedBytes = new byte[0]; _hashedValue = StringUtils.EMPTY; } public MessageDigestResult(byte[] hashedBytes, String hashedValue) { _hashedBytes = hashedBytes; _hashedValue = hashedValue; } /** * Returns the computed hash as an array of bytes. * * @return the computed hash as an array of bytes. */ public byte[] getHashedBytes() { return _hashedBytes; } /** * Returns the hexadecimal representation of the hash value. * * @return the hexadecimal representation of the hash value. */ public String getHashedValue() { return _hashedValue; } /** * Checks whether this is result represents an empty one or not. * * @return true if this result represents an empty one. */ public boolean isEmpty() { return _hashedBytes.length == 0 && _hashedValue.isEmpty(); } @Override public int hashCode() { int hash = 5; hash = 61 * hash + Arrays.hashCode(_hashedBytes); hash = 61 * hash + Objects.hashCode(_hashedValue); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof final MessageDigestResult other)) { return false; } if (!Objects.equals(_hashedValue, other._hashedValue)) { return false; } return Arrays.equals(_hashedBytes, other._hashedBytes); } @Override public String toString() { return getHashedValue(); } }
2,714
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
NamedMessageDigestResult.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/hashing/NamedMessageDigestResult.java
/* * Copyright (C) 2020 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.hashing; import java.util.Objects; /** * Aggregates a {@link MessageDigestResult} and holds a name attribute. * * @author Matthias Fussenegger */ public final class NamedMessageDigestResult { private final MessageDigestResult _messageDigestResult; private final String _name; public NamedMessageDigestResult(MessageDigestResult result, String name) { _messageDigestResult = result; _name = name; } /** * Returns the aggregated {@link MessageDigestResult}. * * @return the aggregated {@link MessageDigestResult}. */ public MessageDigestResult getMessageDigestResult() { return _messageDigestResult; } @Override public int hashCode() { int hash = 7; hash = 79 * hash + Objects.hashCode(_messageDigestResult); hash = 79 * hash + Objects.hashCode(_name); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final NamedMessageDigestResult other = (NamedMessageDigestResult) obj; if (!Objects.equals(_name, other._name)) { return false; } return Objects.equals(_messageDigestResult, other._messageDigestResult); } @Override public String toString() { return _messageDigestResult.toString() + ":" + _name; } }
2,258
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
MessageDigestProvider.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/hashing/MessageDigestProvider.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.hashing; import org.gzipper.java.application.util.StringUtils; import org.gzipper.java.util.Log; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @author Matthias Fussenegger */ public class MessageDigestProvider { private final MessageDigest _messageDigest; public MessageDigestProvider(MessageDigest messageDigest) { _messageDigest = messageDigest; } /** * Factory method to create a new instance of {@link MessageDigestProvider}. * * @param algorithm the algorithm for the {@link MessageDigest}. * @return a new instance of {@link MessageDigestProvider}. * @throws NoSuchAlgorithmException if the specified algorithm (its name) * does not exist. */ public static MessageDigestProvider createProvider( MessageDigestAlgorithm algorithm) throws NoSuchAlgorithmException { String name = algorithm.getAlgorithmName(); MessageDigest msgDigest = MessageDigest.getInstance(name); return new MessageDigestProvider(msgDigest); } /** * Returns the algorithm name of the aggregated {@link MessageDigest}. * * @return the algorithm name of the aggregated {@link MessageDigest}. */ public String getAlgorithmName() { return _messageDigest.getAlgorithm(); } /** * Computes a hash from the current state of the digest of the aggregated * {@link MessageDigest} and returns the result wrapped in * {@link MessageDigestResult} together with its hexadecimal representation. * * @return result object which holds the computed values. */ public MessageDigestResult computeHash() { final byte[] result = _messageDigest.digest(); return new MessageDigestResult(result, convertToHex(result)); } /** * Computes and then returns the hash value of the specified bytes using the * specified message digest algorithm. If the specified algorithm, for * whatever reason, does not exist, an empty result is returned. * * @param bytes the bytes to be processed. * @param algo the algorithm to be used. * @return result object which holds the computed values. */ public static MessageDigestResult computeHash(byte[] bytes, MessageDigestAlgorithm algo) { try { final String name = algo.getAlgorithmName(); final MessageDigest msgDigest = MessageDigest.getInstance(name); byte[] result = msgDigest.digest(bytes); return new MessageDigestResult(result, convertToHex(result)); } catch (NoSuchAlgorithmException ex) { Log.e("Specified message digest algorithm does not exist", ex); } // return an empty result if something went wrong return new MessageDigestResult(new byte[0], StringUtils.EMPTY); } /** * Updates the digest of the aggregated {@link MessageDigest}. * * @param bytes the bytes to be processed. * @param offset starting index in array. * @param length the length to be processed, starting at {@code offset}. */ public void updateHash(byte[] bytes, int offset, int length) { _messageDigest.update(bytes, offset, length); } /** * Resets the aggregated {@link MessageDigest} for further use. */ public void reset() { _messageDigest.reset(); } private static String convertToHex(byte[] bytes) { final StringBuilder sb = new StringBuilder(); for (byte b : bytes) { String formatted = String.format("%02X", b); sb.append(formatted); } return sb.toString(); } }
4,453
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Predicates.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/predicates/Predicates.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.predicates; import java.util.function.Predicate; /** * @author Matthias Fussenegger */ public final class Predicates { private Predicates() { throw new AssertionError("Holds static members only"); } /** * Creates a new {@link Predicate} which always evaluates to <b>true</b>. * * @param <T> the type of the object that is to be consumed by the predicate * and thus the type of the input to the predicate. * @return a new instance of {@link Predicate} with the specified type. */ public static <T> Predicate<T> createAlwaysTrue() { return p -> true; } }
1,412
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
PatternPredicate.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/predicates/PatternPredicate.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.predicates; import java.util.function.Predicate; import java.util.regex.Pattern; /** * Simple filter predicate which uses a regular expression to test a string * against a {@link Pattern}. * * @author Matthias Fussenegger */ public final class PatternPredicate implements Predicate<String> { private final Pattern _pattern; public PatternPredicate(Pattern pattern) { _pattern = pattern; } @Override public boolean test(String t) { return _pattern.matcher(t).find(); } }
1,254
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Notifier.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/observer/Notifier.java
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.observer; /** * Simple observable which supports generic types. * * @param <T> type of the value. * @author Matthias Fussenegger */ public interface Notifier<T> { /** * Each notifier should provide a unique identifier so it can be easier * recognized by any listener. * <p> * This is mainly used to avoid recalculations using the {@code hashCode()} * method, which provides a hash code for this object. * * @return the unique identifier of this instance. */ int getId(); /** * Returns the currently associated value. * * @return the currently associated value. */ T getValue(); /** * Replaces the currently associated value with the specified one. * * @param value the value to be set. */ void setValue(T value); /** * Replaces the currently associated value with the specified one, sets the * current status to changed and then notifies all attached listeners. * <p> * To be more detailed, this default implementation first calls * {@link #setValue(java.lang.Object)}, then {@link #setChanged()} and last * but not least {@link #notifyListeners()}. * * @param value the value to be changed. */ default void changeValue(T value) { setValue(value); setChanged(); notifyListeners(); } /** * Notifies all attached listeners if {@link #hasChanged()} returns true. If * so, {@link #clearChanged()} will be called right after. */ void notifyListeners(); /** * Checks whether the value has changed or not. * * @return true if value has changed, false otherwise. */ boolean hasChanged(); /** * Sets the status to changed, {@link #hasChanged()} now returns true. */ void setChanged(); /** * Clears the status, {@link #hasChanged()} now returns false. */ void clearChanged(); /** * Attaches a new listener if it is not yet attached. * * @param listener the listener to be attached. */ void attach(Listener<T> listener); /** * Detaches the specified listener. * * @param listener the listener to be detached. */ void detach(Listener<T> listener); /** * Removes all attached listeners. */ void clearListeners(); }
3,208
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Listener.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/observer/Listener.java
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.observer; /** * Simple observer which supports generic types. * * @param <T> type of the value. * @author Matthias Fussenegger */ public interface Listener<T> { /** * Called by a {@link Notifier} if its associated value has been updated. * * @param notifier the source of this call. * @param value the updated value. */ void update(Notifier<T> notifier, T value); }
1,143
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
NotifierImpl.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/observer/NotifierImpl.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.observer; import java.util.List; import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; /** * @param <T> type of the value. * @author Matthias Fussenegger */ public class NotifierImpl<T> implements Notifier<T> { /** * Unique identifier of this instance. */ private final int _id = hashCode(); /** * Listeners to be notified if the associated value has been updated. */ private final List<Listener<T>> _listeners = new CopyOnWriteArrayList<>(); /** * True if value has changed, false otherwise. */ private boolean _hasChanged = false; /** * The associated value which may change. */ private T _value; @Override public int getId() { return _id; } @Override public final synchronized T getValue() { return _value; } @Override public final synchronized void setValue(T value) { _value = value; } @Override public final void notifyListeners() { if (hasChanged()) { _listeners.forEach((listener) -> listener.update(this, _value)); clearChanged(); } } @Override public final synchronized boolean hasChanged() { return _hasChanged; } @Override public final synchronized void setChanged() { _hasChanged = true; } @Override public final synchronized void clearChanged() { _hasChanged = false; } @Override public final void attach(Listener<T> listener) { Objects.requireNonNull(listener); if (!_listeners.contains(listener)) { _listeners.add(listener); } } @Override public final void detach(Listener<T> listener) { _listeners.remove(listener); } @Override public final void clearListeners() { _listeners.clear(); } }
2,613
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Interruptible.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/concurrency/Interruptible.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.concurrency; /** * @author Matthias Fussenegger */ @FunctionalInterface public interface Interruptible { /** * Interrupts any further processing. */ void interrupt(); }
925
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
AppUtils.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/util/AppUtils.java
/* * Copyright (C) 2019 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.util; import org.gzipper.java.util.Log; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; /** * Utility class that provides application-specific methods for e.g. receiving * resources from the resource path of a class. * * @author Matthias Fussenegger */ public final class AppUtils { private static final String JAVA_VERSION = determineJavaVersion(); private AppUtils() { throw new AssertionError("Holds static members only"); } private static String determineJavaVersion() { String version = System.getProperty("java.version"); int pos = version.indexOf('.'); if (pos != -1) { // found pos = version.indexOf('.', pos + 1); if (pos != -1) { // found version = version.substring(0, pos); } } return version; } private static String createTemporaryFile(BufferedInputStream bis, String tempName) throws IOException { final File file = File.createTempFile(tempName, ".tmp"); try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) { int readBytes; byte[] bytes = new byte[1024]; while ((readBytes = bis.read(bytes)) != -1) { bos.write(bytes, 0, readBytes); } } file.deleteOnExit(); return file.getPath(); } /** * Determines the current Java version and returns the major version of Java * as string. For e.g. Java 8, this would return {@code 1.8}. * * @return the Java major version as string. */ public static String getJavaVersion() { return JAVA_VERSION; } /** * Returns the resource path of the specified class as string. The file will * be stored in the system's temporary folder with the file extension * <b>.tmp</b>. The file will be deleted on JVM termination. * * @param clazz the class of which to receive the resource path. * @param name the name of the resource to receive. * @return the resource path of the specified class. * @throws URISyntaxException if URL conversion failed. */ public static String getResource(Class<?> clazz, String name) throws URISyntaxException, FileNotFoundException { String resource = null; final URL url = clazz.getResource(name); if (url == null) { throw new FileNotFoundException("Resource not found: " + name); } if (url.toString().startsWith("jar:")) { String tempName = name.substring(name.lastIndexOf('/') + 1); var resourceStream = clazz.getResourceAsStream(name); if (resourceStream == null) { throw new FileNotFoundException("Resource not found: " + name); } try (BufferedInputStream bis = new BufferedInputStream(resourceStream)) { resource = createTemporaryFile(bis, tempName); } catch (IOException ex) { Log.e(ex.getLocalizedMessage(), ex); } } else { resource = Paths.get(url.toURI()).toString(); } return resource; } /** * Returns the decoded root path of the application's JAR-file. * * @param clazz the class of which to receive the root path. * @return the decoded root path of the JAR-file. */ public static String getDecodedRootPath(Class<?> clazz) { String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath(); final File jarFile = new File(path); final int cutLength = determineCutLength(jarFile); String decPath; // to hold decoded path of JAR-file if (System.getProperty("os.name").startsWith("Windows")) { decPath = URLDecoder.decode(path.substring(1, path.length() - cutLength), StandardCharsets.UTF_8); } else { decPath = URLDecoder.decode(path.substring(0, path.length() - cutLength), StandardCharsets.UTF_8); } return decPath; } private static int determineCutLength(File f) { int cutLength = 0; if (!f.isDirectory()) { cutLength = f.getName().length(); } return cutLength; } }
5,277
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
TaskHandler.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/util/TaskHandler.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.util; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Handler used to execute tasks via {@link ExecutorService}. * * @author Matthias Fussenegger */ public final class TaskHandler implements AutoCloseable { private final ExecutorService _executorService; public TaskHandler(ExecutorType type) { _executorService = type.getExecutorService(); } /** * Executes the specified task. * * @param task the task to be executed. * @return a {@link Future} which can be used to manipulate the task. */ public synchronized Future<?> submit(Runnable task) { return _executorService.submit(task); } /** * Executes the specified task. * * @param <T> the type of the task's result. * @param task the task to be executed. * @return a {@link Future} representing the pending completion of the task. */ public synchronized <T> Future<T> submit(Callable<T> task) { return _executorService.submit(task); } @Override public void close() { _executorService.shutdown(); } public enum ExecutorType { CACHED { @Override ExecutorService getExecutorService() { return Executors.newCachedThreadPool(); } }, QUEUED { @Override ExecutorService getExecutorService() { return Executors.newSingleThreadExecutor(); } }; abstract ExecutorService getExecutorService(); } }
2,389
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
MapUtils.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/util/MapUtils.java
/* * Copyright (C) 2020 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.util; import java.util.Map; /** * Utility class that provides methods for instances of {@link Map}. * * @author Matthias Fussenegger */ public final class MapUtils { private MapUtils() { throw new AssertionError("Holds static members only"); } /** * Checks whether the given list is {@code null} or empty. * * @param <K> the type of the key of this map. * @param <V> the type of the value that is mapped to the key. * @param map the map to be checked. * @return true if map is {@code null} or empty, false otherwise. */ public static <K, V> boolean isNullOrEmpty(Map<K, V> map) { return map == null || map.isEmpty(); } }
1,433
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
ListUtils.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/util/ListUtils.java
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.util; import java.util.List; /** * Utility class that provides methods for instances of {@link List}. * * @author Matthias Fussenegger */ public final class ListUtils { private ListUtils() { throw new AssertionError("Holds static members only"); } /** * Checks whether the given list is {@code null} or empty. * * @param <T> types of which this list consists of. * @param list the list to be checked. * @return true if list is {@code null} or empty, false otherwise. */ public static <T> boolean isNullOrEmpty(List<T> list) { return list == null || list.isEmpty(); } }
1,378
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
FileUtils.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/util/FileUtils.java
/* * Copyright (C) 2019 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.util; import org.gzipper.java.application.model.ArchiveType; import org.gzipper.java.util.Log; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; /** * Utility class that provides methods for different kinds of file operations. * * @author Matthias Fussenegger */ public final class FileUtils { private FileUtils() { throw new AssertionError("Holds static members only"); } private static String getArchiveTypeExtensionName(String filename, List<ArchiveType> archiveTypes) { for (var archiveType : archiveTypes) { String[] extensionNames = archiveType.getExtensionNames(false); for (String extensionName : extensionNames) { if (filename.endsWith(extensionName)) return extensionName; } } return null; } private static String getArchiveTypeExtensionName(String filename) { var archiveTypes = ArchiveType.values(); var tarArchiveTypes = new ArrayList<ArchiveType>(); var nonTarArchiveTypes = new ArrayList<ArchiveType>(); Arrays.stream(archiveTypes).forEach(type -> { if (type.getName().toLowerCase().startsWith("tar")) { tarArchiveTypes.add(type); } else { nonTarArchiveTypes.add(type); } }); String extensionName = getArchiveTypeExtensionName(filename, tarArchiveTypes); if (extensionName != null) return extensionName; return getArchiveTypeExtensionName(filename, nonTarArchiveTypes); } private static class SizeValueHolder { private long _size; SizeValueHolder() { _size = 0; } } /** * Validates the specified path, which has to exist. * * @param path the path as string to be validated. * @return true if file exists, false otherwise. */ public static boolean isValid(String path) { final File file = new File(path); return file.exists(); } /** * Validates the specified path, which has to be a normal file. * * @param path the path as string to be validated. * @return true if file is a file, false otherwise. */ public static boolean isValidFile(String path) { final File file = new File(path); return file.isFile(); } /** * Validates the specified path, which has to be the full name of a file * that shall be created and therefore does not exist yet. * * @param path the path as string to be validated. * @return true if the parent file is a directory, false otherwise. */ public static boolean isValidOutputFile(String path) { final File file = new File(path); final File parentFile = file.getParentFile(); return parentFile != null && parentFile.isDirectory() && !parentFile.getName().endsWith(" "); } /** * Validates the specified path, which has to be the path of a directory. * * @param path the path as string to be validated. * @return true if file exists and is a directory, false otherwise. */ public static boolean isValidDirectory(String path) { final File file = new File(path); return file.isDirectory(); } /** * Checks whether the filename contains illegal characters. * * @param filename the name to be checked for illegal characters. * @return true if filename contains illegal characters, false otherwise. */ public static boolean containsIllegalChars(String filename) { final File file = new File(filename); if (!file.isDirectory()) { final String name = file.getName(); return name.contains("<") || name.contains(">") || name.contains("/") || name.contains("\\") || name.contains("|") || name.contains(":") || name.contains("*") || name.contains("\"") || name.contains("?"); } return filename.contains("<") || filename.contains(">") || filename.contains("|") || filename.contains("*") || filename.contains("\"") || filename.contains("?"); } /** * Concatenates two file names. Before doing so, a check will be performed * whether the first filename ends with a separator. If the separator is * missing it will be added. * * @param filename filename as string. * @param append the filename to be appended. * @return an empty string if either any of the parameters is {@code null} * or empty. Otherwise, the concatenated absolute path is returned. */ public static String combine(String filename, String append) { if (StringUtils.isNullOrEmpty(filename) || StringUtils.isNullOrEmpty(append)) { return StringUtils.EMPTY; } filename = normalize(filename); final String absolutePath; if (filename.endsWith("/")) { absolutePath = filename; } else { absolutePath = filename + "/"; } return absolutePath + append; } /** * Returns the file name extension(s) of a specified filename. * * @param filename the name of the file as string. * @return file name extension(s) including period or an empty string if the * specified filename has no file name extension. */ public static String getExtension(String filename) { return getExtension(filename, false); } /** * Returns the file name extension(s) of a specified filename. * * @param filename the name of the file as string. * @param considerArchiveTypeExtensions true to consider file name extensions of known archive types. * @return file name extension(s) including period or an empty string if the * specified filename has no file name extension. */ public static String getExtension(String filename, boolean considerArchiveTypeExtensions) { final String normalizedFilename = normalize(filename); if (considerArchiveTypeExtensions) { String extensionName = getArchiveTypeExtensionName(normalizedFilename); if (extensionName != null) return extensionName; } final int lastIndexOfFileSeparator = normalizedFilename.lastIndexOf('/'); final int indexOfPeriod = normalizedFilename.indexOf('.', lastIndexOfFileSeparator); return indexOfPeriod > 0 ? normalizedFilename.substring(indexOfPeriod) : StringUtils.EMPTY; } /** * Returns the name of the specified filename including its file name extension. * * @param filename the name of the file as string. * @return the name of the file including its file name extension. */ public static String getName(String filename) { filename = normalize(filename); int lastSeparatorIndex = filename.lastIndexOf('/'); if (lastSeparatorIndex == -1) { lastSeparatorIndex = 0; // no separator present } else { ++lastSeparatorIndex; } return filename.substring(lastSeparatorIndex); } /** * Returns the display name of the specified filename without its extension. * * @param filename the name of the file as string. * @return the display name of the file without its file name extension. */ public static String getDisplayName(String filename) { final String normalizedFilename = normalize(filename); int lastIndexOfFileSeparator = normalizedFilename.lastIndexOf('/'); int lastIndexOfPeriod = filename.lastIndexOf('.'); if (lastIndexOfFileSeparator == -1) { lastIndexOfFileSeparator = 0; // no separator present } else { ++lastIndexOfFileSeparator; } if (lastIndexOfPeriod == -1) { lastIndexOfPeriod = normalizedFilename.length(); } return normalizedFilename.substring(lastIndexOfFileSeparator, lastIndexOfPeriod); } /** * Returns the canonical path if possible or otherwise the absolute path. * * @param file the file of which to get the path of. * @return the canonical path if possible or otherwise the absolute path. */ public static String getPath(File file) { try { return file.getCanonicalPath(); } catch (IOException ex) { Log.e("Canonical path could not be computed", ex); return file.getAbsolutePath(); } } /** * Returns the full name of the parent directory of the specified file name. * * @param filename the file name of which to receive the parent directory. * @return the parent directory of the specified file name or an empty * string if the specified file name does not have a parent. */ public static String getParent(String filename) { final File file = new File(filename); String parent = file.getParent(); return parent != null ? parent : StringUtils.EMPTY; } /** * Copies a file from the specified source to destination. If no copy * options are specified, the file at the destination will not be replaced * in case it already exists. * * @param src the source path. * @param dst the destination path. * @param options optional copy options. * @throws IOException if an I/O error occurs. */ public static void copy(String src, String dst, CopyOption... options) throws IOException { if (options == null) { options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES}; } Files.copy(Paths.get(src), Paths.get(dst), options); } /** * Normalizes the specified path. After the normalization, all file separators are equal to {@code /}. * * @param path the path to be normalized. * @return a normalized version of the specified path. */ public static String normalize(String path) { return path.replace('\\', '/'); } /** * Removes the extension from the specified {@param filename}. * * @param filename the file name to remove the extension from. * @return the specified file name without the extension (if any). */ public static String removeExtension(String filename) { final String normalizedFilename = normalize(filename); final int lastIndexOfFileSeparator = normalizedFilename.lastIndexOf('/'); final int indexOfPeriod = normalizedFilename.indexOf('.', lastIndexOfFileSeparator); return indexOfPeriod > 0 ? normalizedFilename.substring(0, indexOfPeriod) : filename; } /** * Returns the file size of the specified file. * * @param file the file whose size is to be returned. * @param filter the filter to be applied. * @return the size of the file or {@code 0} if the specified predicate * evaluates to {@code false}. */ public static long fileSize(File file, Predicate<String> filter) { return filter.test(file.getName()) ? file.length() : 0; } /** * Traverses the specified path and returns the size of all children. * * @param path the path to be traversed. * @param filter the filter to be applied. * @return the size of all children. */ public static long fileSizes(Path path, Predicate<String> filter) { final SizeValueHolder holder = new SizeValueHolder(); try { Files.walkFileTree(path, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { String name = file.getFileName().toString(); if (filter.test(name)) { holder._size += attrs.size(); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException ex) { Log.e(file + " skipped. Progress may be inaccurate", ex); return FileVisitResult.CONTINUE; // skip folder that can't be traversed } @Override public FileVisitResult postVisitDirectory(Path dir, IOException ex) { if (ex != null) { Log.e(dir + " could not be traversed. Progress may be inaccurate", ex); } return FileVisitResult.CONTINUE; } }); } catch (IOException ex) { throw new AssertionError(ex); } return holder._size; } /** * Generates a unique file name using the specified parameters. * * @param path the file path including only the directory. * @param name the name of the file of which to generate a unique version. * @return a unique filename that consists of the path, name, suffix and file name extension (if any). */ public static String generateUniqueFilename(String path, String name) { return generateUniqueFilename(path, name, 1); } /** * Generates a unique file name using the specified parameters. * * @param path the file path including only the directory. * @param name the name of the file of which to generate a unique version. * @param beginSuffix the suffix to begin with (will be incremented). * @return a unique filename that consists of the path, name, suffix and file name extension (if any). */ public static String generateUniqueFilename(String path, String name, int beginSuffix) { final String extension = getExtension(name, true); if (!extension.isEmpty()) { name = removeExtension(name); } return generateUniqueFilename(path, name, extension, beginSuffix); } /** * Generates a unique file name using the specified parameters. * * @param path the file path including only the directory. * @param name the name of the file of which to generate a unique version. * @param ext the name of the file extension. * @return a unique filename that consists of the path, name, suffix and file name extension. */ public static String generateUniqueFilename(String path, String name, String ext) { return generateUniqueFilename(path, name, ext, 1); } /** * Generates a unique file name using the specified parameters. * * @param path the file path including only the directory. * @param name the name of the file of which to generate a unique version. * @param ext the name of the file extension. * @param beginSuffix the suffix to begin with (will be incremented). This * parameter will be ignored if its value is less or equal zero. * @return a unique filename that consists of the path, name, suffix and file name extension. */ public static String generateUniqueFilename(String path, String name, String ext, int beginSuffix) { path = normalize(path); name = normalize(name); int suffix = beginSuffix > 0 ? beginSuffix : 1; // to be appended boolean isFirst = true; // to ignore suffix on first check final StringBuilder filename = new StringBuilder(); if (ext.startsWith("*")) { // ignore asterisk if any ext = ext.substring(1); } final String trimmedPath = path.trim(); String uniqueFilename = FileUtils.combine(trimmedPath, name + ext); if (!FileUtils.isValid(uniqueFilename)) return uniqueFilename; // return as it is if not exists do { // as long as file exists if (isFirst && beginSuffix <= 0) { filename.append(name).append(ext); } else { filename.append(name).append(suffix).append(ext); ++suffix; } isFirst = false; uniqueFilename = FileUtils.combine(trimmedPath, filename.toString()); filename.setLength(0); // clear } while (FileUtils.isValidFile(uniqueFilename)); return uniqueFilename; } }
17,195
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
StringUtils.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/util/StringUtils.java
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.util; /** * Utility class that provides methods for instances of {@link String}. * * @author Matthias Fussenegger */ public final class StringUtils { /** * An empty string. */ public static final String EMPTY = ""; private StringUtils() { throw new AssertionError("Holds static members only"); } /** * Checks whether the given string is {@code null} or empty. * * @param string the string to be checked. * @return true if string is {@code null} or empty, false otherwise. */ public static boolean isNullOrEmpty(String string) { return string == null || string.isEmpty(); } }
1,396
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
CompressorAlgorithm.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/CompressorAlgorithm.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorOutputStream; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.application.util.StringUtils; import org.gzipper.java.exceptions.GZipperException; import java.io.*; /** * @author Matthias Fussenegger */ public abstract class CompressorAlgorithm extends AbstractAlgorithm { @Override public final void compress(File[] files, String location, String name) throws IOException { initAlgorithmProgress(files); String fullname = FileUtils.combine(location, name); if (files.length > 0 && files[0].isFile()) { // handling first file only, this way the current // API does not need to be changed/more complicated final File file = files[0]; // check predicate first if (!filterPredicate.test(file.getName())) { return; // ignore file } final var options = new CompressorOptions(file.getName(), compressionLevel); try (final FileInputStream fis = new FileInputStream(file); final BufferedInputStream bis = new BufferedInputStream(fis); final CompressorOutputStream cos = makeCompressorOutputStream( new BufferedOutputStream(new FileOutputStream(fullname)), options)) { final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int readBytes; while (!interrupt && (readBytes = bis.read(buffer)) != -1) { cos.write(buffer, 0, readBytes); updateProgress(readBytes); } } } else { throw new IOException(GZipperException.createWithReason( GZipperException.Reason.NO_DIR_SUPPORTED, "Directories are not supported!")); } } @Override public final void extract(String location, String fullname) throws IOException { final File archive = new File(fullname); // check predicate first if (!filterPredicate.test(archive.getName())) { return; // ignore file } initAlgorithmProgress(archive); CompressorOptions options = new CompressorOptions(); try (final CompressorInputStream gcis = makeCompressorInputStream( new BufferedInputStream(new FileInputStream(archive)), options)) { final File outputFile; if (StringUtils.isNullOrEmpty(options._name)) { outputFile = new File(FileUtils.generateUniqueFilename(location, FileUtils.getDisplayName(fullname))); } else { // create output file with name as defined in header outputFile = new File(FileUtils.generateUniqueFilename(location, options._name)); } try (final BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(outputFile))) { final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int readBytes; while (!interrupt && (readBytes = gcis.read(buffer)) != -1) { bos.write(buffer, 0, readBytes); updateProgress(readBytes); } } } } /** * Creates a new instance of {@link CompressorInputStream}. This is used so * that specific algorithms can e.g. apply individual parameters. * * @param stream the {@link InputStream} being used when creating a new * {@link CompressorInputStream}. * @param options Options that may be applied. * @return new instance of {@link CompressorInputStream}. * @throws java.io.IOException if an I/O error occurs. */ protected abstract CompressorInputStream makeCompressorInputStream( InputStream stream, CompressorOptions options) throws IOException; /** * Creates a new instance of {@link CompressorOutputStream}. This is used so * that specific algorithms can e.g. apply individual parameters. * * @param stream the {@link OutputStream} being used when creating a new * {@link CompressorOutputStream}. * @param options Options that may be applied. * @return new instance of {@link CompressorOutputStream}. * @throws IOException if an I/O error occurs. */ protected abstract CompressorOutputStream makeCompressorOutputStream( OutputStream stream, CompressorOptions options) throws IOException; /** * Consists of additional information for the subclass and functions as a * data exchange object for e.g. the file name. */ protected static class CompressorOptions { /** * The name of the archive or the file to be compressed. */ private String _name; /** * The compression level to be applied if supported. */ private int _level; public CompressorOptions() { } public CompressorOptions(String name, int level) { _name = name; _level = level; } /** * Returns the name of the archive or the file to be compressed. * * @return the name of the archive or the file to be compressed. */ public final String getName() { return _name; } /** * Sets the name of the archive or the file to be compressed. * * @param name the name of the archive or the file to be compressed. */ public final void setName(String name) { _name = name; } /** * Returns the compression level. * * @return the compression level. */ public final int getLevel() { return _level; } } }
6,690
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
ArchivingAlgorithm.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/ArchivingAlgorithm.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm; import org.apache.commons.compress.archivers.*; import org.apache.commons.compress.compressors.CompressorException; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorOutputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.application.util.StringUtils; import org.gzipper.java.i18n.I18N; import org.gzipper.java.util.Log; import java.io.*; import java.util.Arrays; /** * @author Matthias Fussenegger */ public abstract class ArchivingAlgorithm extends AbstractAlgorithm { /** * Type of the archive stream. */ protected final String _archiveType; /** * Type of compressor stream. */ protected final String _compressionType; /** * Factory to create archive streams. */ protected final ArchiveStreamFactory _archiveStreamFactory; /** * Factory to create compressor streams. */ protected final CompressorStreamFactory _compressorStreamFactory; /** * Creates a new instance for archiving operations. * * @param archiveType the type of the archive. * @param compressionType the type of the compressor stream. */ protected ArchivingAlgorithm(String archiveType, String compressionType) { _archiveType = archiveType; _compressionType = compressionType; _archiveStreamFactory = new ArchiveStreamFactory(); _compressorStreamFactory = new CompressorStreamFactory(); } @Override public final void extract(String location, String fullname) throws IOException, ArchiveException, CompressorException { final File archive = new File(fullname); initAlgorithmProgress(archive); try (final FileInputStream fis = new FileInputStream(archive); final BufferedInputStream bis = new BufferedInputStream(fis); final CompressorInputStream cis = makeCompressorInputStream(bis); final ArchiveInputStream ais = cis != null ? makeArchiveInputStream(cis) : makeArchiveInputStream(bis)) { ArchiveEntry entry = ais.getNextEntry(); fullname = FileUtils.normalize(fullname); final String displayName = FileUtils.getDisplayName(fullname); final String outputFolderName = FileUtils.combine(location, displayName); final File outputFolder = new File(outputFolderName); if (createOutputFolderIfNotExists(outputFolder)) { Log.e(I18N.getString("errorCreatingDirectory.text", FileUtils.getPath(outputFolder))); throw new IOException(String.format("%s could not be created", FileUtils.getPath(outputFolder))); } while (!interrupt && entry != null) { final String entryName = entry.getName(); if (filterPredicate.test(entryName)) { // check predicate first final String uniqueName = FileUtils.generateUniqueFilename( FileUtils.getPath(outputFolder), entryName); final File newFile = new File(uniqueName); // check if entry contains a directory if (entryName.indexOf('/') > -1) { if (!newFile.getParentFile().exists()) { // also create parent directories by calling "mkdirs" if (!newFile.getParentFile().mkdirs()) { final String parentFilePath = FileUtils.getPath(newFile.getParentFile()); Log.e(I18N.getString("errorCreatingDirectory.text", parentFilePath)); throw new IOException(String.format("%s could not be created", parentFilePath)); } } } if (!entry.isDirectory()) { // create new output stream and write bytes to file try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile))) { final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int readBytes; while (!interrupt && (readBytes = ais.read(buffer)) != -1) { bos.write(buffer, 0, readBytes); updateProgress(readBytes); } } catch (IOException ex) { if (!interrupt) { Log.e(ex.getLocalizedMessage(), ex); Log.e("{0}\n{1}", I18N.getString("errorWritingFile.text"), newFile.getPath() ); } throw ex; // re-throw } } } if (!interrupt) { entry = ais.getNextEntry(); } } } } @Override public final void compress(File[] files, String location, String name) throws IOException, ArchiveException, CompressorException { String archiveName = FileUtils.combine(location, name); initAlgorithmProgress(files); try (final FileOutputStream fos = new FileOutputStream(archiveName); final BufferedOutputStream bos = new BufferedOutputStream(fos); final CompressorOutputStream cos = makeCompressorOutputStream(bos); final ArchiveOutputStream aos = cos != null ? makeArchiveOutputStream(cos) : makeArchiveOutputStream(bos)) { String basePath = StringUtils.EMPTY; compress(files, basePath, aos, archiveName); } } private void compress(File[] files, String base, ArchiveOutputStream aos, String archiveName) throws IOException { final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int readBytes; if (files.length > 0) { for (int i = 0; !interrupt && i < files.length; ++i) { // create next file and define entry name based on folder level final File newFile = files[i]; final String entryName = base + newFile.getName(); if (newFile.isFile()) { // check predicate first if (!filterPredicate.test(newFile.getName())) { continue; // skip entry } // read and compress the file try (BufferedInputStream buf = new BufferedInputStream(new FileInputStream(newFile))) { // create next archive entry and put it on output stream ArchiveEntry entry = aos.createArchiveEntry(newFile, entryName); aos.putArchiveEntry(entry); // write bytes to file while (!interrupt && (readBytes = buf.read(buffer)) != -1) { aos.write(buffer, 0, readBytes); updateProgress(readBytes); } aos.closeArchiveEntry(); } catch (IOException ex) { if (!interrupt) { Log.e(ex.getLocalizedMessage(), ex); Log.e("{0}\n{1}", I18N.getString("errorReadingFile.text"), newFile.getPath()); throw ex; // re-throw } } } else if (newFile.isDirectory()) { final File[] children = getChildrenExcludingArchiveToBeCreated(archiveName, newFile); compress(children, entryName + "/", aos, archiveName); } else { Log.i(I18N.getString("skippingUnsupportedFile.text"), true, FileUtils.getPath(newFile)); } } } } private boolean createOutputFolderIfNotExists(File outputFolder) { return !outputFolder.exists() && !outputFolder.mkdir(); } private File[] getChildrenExcludingArchiveToBeCreated(String archiveName, File directory) { File[] children = getFiles(FileUtils.getPath(directory)); children = Arrays.stream(children) .filter(file -> !FileUtils.getPath(file).equals(archiveName)) .toArray(File[]::new); return children; } /** * Creates a new instance of an {@link ArchiveInputStream}. This can be used * so that specific algorithms can e.g. skip the archive stream. * * @param stream the {@link InputStream} being used when creating a new * {@link ArchiveInputStream}. * @return new instance of {@link ArchiveInputStream}. * @throws ArchiveException if an error related to the archiver occurs. */ protected ArchiveInputStream makeArchiveInputStream(InputStream stream) throws ArchiveException { return _archiveStreamFactory.createArchiveInputStream(_archiveType, stream); } /** * Creates a new instance of {@link CompressorInputStream}. This can be used * so that specific algorithms can e.g. apply individual parameters. * * @param stream the {@link InputStream} being used when creating a new * {@link CompressorInputStream}. * @return new instance of {@link CompressorInputStream}. * @throws java.io.IOException if an I/O error occurs. * @throws CompressorException if an error related to the compressor occurs. */ protected CompressorInputStream makeCompressorInputStream(InputStream stream) throws IOException, CompressorException { return _compressorStreamFactory.createCompressorInputStream(_compressionType, stream); } /** * Creates a new instance of an {@link ArchiveOutputStream}. This can be * used so that specific algorithms can e.g. skip the archive stream. * * @param stream the {@link OutputStream} being used when creating a new * {@link ArchiveOutputStream}. * @return new instance of {@link ArchiveOutputStream}. * @throws ArchiveException if an error related to the archiver occurs. */ protected ArchiveOutputStream makeArchiveOutputStream(OutputStream stream) throws ArchiveException { return _archiveStreamFactory.createArchiveOutputStream(_archiveType, stream); } /** * Creates a new instance of {@link CompressorOutputStream}. This can be * used so that specific algorithms can e.g. apply individual parameters. * * @param stream the {@link OutputStream} being used when creating a new * {@link CompressorOutputStream}. * @return new instance of {@link CompressorOutputStream}. * @throws IOException if an I/O error occurs. * @throws CompressorException if an error related to the compressor occurs. */ protected CompressorOutputStream makeCompressorOutputStream(OutputStream stream) throws IOException, CompressorException { return _compressorStreamFactory.createCompressorOutputStream(_compressionType, stream); } }
12,254
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
CompressionAlgorithm.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/CompressionAlgorithm.java
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.compressors.CompressorException; import org.gzipper.java.application.ArchiveInfo; import org.gzipper.java.application.concurrency.Interruptible; import org.gzipper.java.application.observer.Notifier; import java.io.File; import java.io.IOException; import java.util.function.Predicate; /** * Any implementing class offers methods for compression and decompression. * * @author Matthias Fussenegger */ public interface CompressionAlgorithm extends Interruptible, Notifier<Integer> { /** * The default buffer size for chunks. */ int DEFAULT_BUFFER_SIZE = 8192; /** * Compresses files using the algorithm of the concrete class with default * settings and stores an archive to the specified path. * * @param files the files selected from the file chooser. * @param location defines where to store the archive. * @param name the name of the archive without the directory path. * @throws IOException if an I/O error occurs. * @throws ArchiveException if an error related to the archiver occurs. * @throws CompressorException if an error related to the compressor occurs. */ void compress(File[] files, String location, String name) throws IOException, ArchiveException, CompressorException; /** * Compresses files using the algorithm of the concrete class with default * settings and stores an archive to the path specified in * {@link ArchiveInfo}. * * @param info POJO that holds information required for compression. * @throws IOException if an I/O error occurs. * @throws ArchiveException if an error related to the archiver occurs. * @throws CompressorException if an error related to the compressor occurs. */ void compress(ArchiveInfo info) throws IOException, ArchiveException, CompressorException; /** * Extracts an archive using the algorithm of the concrete class and stores * the files of the archive to the specified path. * * @param location the location where to extract the archive. * @param fullname the filename of the archive to extract. * @throws IOException if an I/O error occurs. * @throws ArchiveException if an error related to the archiver occurs. * @throws CompressorException if an error related to the compressor occurs. */ void extract(String location, String fullname) throws IOException, ArchiveException, CompressorException; /** * Extracts an archive using the algorithm of the concrete class and stores * the files of the archive to the path specified in {@link ArchiveInfo}. * * @param info POJO that holds information required for extraction. * @throws IOException if an I/O error occurs. * @throws ArchiveException if an error related to the archiver occurs. * @throws CompressorException if an error related to the compressor occurs. */ void extract(ArchiveInfo info) throws IOException, ArchiveException, CompressorException; /** * Sets the specified {@link Predicate} which will be used as a filter when * compressing files or decompressing archive entries by evaluating the name * of the file or entry. * * @param predicate the {@link Predicate} to be used. */ void setPredicate(Predicate<String> predicate); }
4,273
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
AbstractAlgorithm.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/AbstractAlgorithm.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.compressors.CompressorException; import org.gzipper.java.application.ArchiveInfo; import org.gzipper.java.application.observer.NotifierImpl; import org.gzipper.java.application.predicates.Predicates; import java.io.File; import java.io.IOException; import java.util.Objects; import java.util.function.Predicate; /** * Abstract class that offers generally used attributes and methods for * archiving algorithms. Any class that represents an archiving algorithm should * derive from this class. * * @author Matthias Fussenegger */ public abstract class AbstractAlgorithm extends NotifierImpl<Integer> implements CompressionAlgorithm { /** * If set to true the currently running operation will be interrupted. */ protected volatile boolean interrupt = false; /** * The compression level. Will only be considered if supported by algorithm. */ protected int compressionLevel; /** * Object used to update the progress of the algorithm. */ protected AlgorithmProgress algorithmProgress; /** * Predicate used to filter files or entries when processing archives. */ protected Predicate<String> filterPredicate; /** * The default constructor of this class. */ public AbstractAlgorithm() { // accepts all files/entries since the test result is never false filterPredicate = Predicates.createAlwaysTrue(); } /** * Retrieves files from a specific directory; mandatory for compression. * * @param path the path that contains the files to be compressed. * @return an array of files from the specified path. */ protected final File[] getFiles(String path) { final File dir = new File(path); return dir.listFiles(); } /** * Initializes {@link #algorithmProgress} with the specified files. * * @param files the files to be used for initialization. */ protected final void initAlgorithmProgress(File... files) { algorithmProgress = new AlgorithmProgress(filterPredicate, files); } /** * Updates the progress of the current operation and notifies all attached * listeners if the new progress using {@code Math.rint(double)} is greater * than the previous one. This behavior may be changed by overriding this * method. * * @param readBytes the amount of bytes that have been read so far. */ protected final void updateProgress(long readBytes) { algorithmProgress.updateProgress(readBytes); changeValue(algorithmProgress.getProgress()); } @Override public final void compress(ArchiveInfo info) throws IOException, ArchiveException, CompressorException { final File[] files = new File[Objects.requireNonNull(info.getFiles()).size()]; compressionLevel = info.getLevel(); compress(info.getFiles().toArray(files), info.getOutputPath(), info.getArchiveName()); } @Override public final void extract(ArchiveInfo info) throws IOException, ArchiveException, CompressorException { extract(info.getOutputPath(), info.getArchiveName()); } @Override public final void setPredicate(Predicate<String> predicate) { if (predicate != null) { filterPredicate = predicate; } } @Override public final void interrupt() { interrupt = true; } }
4,246
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
AlgorithmProgress.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/AlgorithmProgress.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm; import org.gzipper.java.application.util.FileUtils; import java.io.File; import java.util.Objects; import java.util.function.Predicate; /** * @author Matthias Fussenegger */ public final class AlgorithmProgress { /** * Total size of the file(s). */ private long _totalSize; /** * Total amount of bytes already read. */ private long _totalBytesRead; AlgorithmProgress(Predicate<String> filter, File... files) { Objects.requireNonNull(filter); Objects.requireNonNull(files); setTotalSize(filter, files); } private void setTotalSize(Predicate<String> filter, File... files) { for (File file : files) { _totalSize += file.isDirectory() ? FileUtils.fileSizes(file.toPath(), filter) : FileUtils.fileSize(file, filter); } } /** * Returns the rounded progress. * * @return the current progress. */ int getProgress() { return (int) Math.round(getProgressPrecise()); } /** * Returns the precise progress. * * @return the current progress. */ double getProgressPrecise() { return ((double) _totalBytesRead / _totalSize) * 100; } /** * Updates the current progress and returns it. The progress is only updated * if it is less or equal {@code 100}. * * @param readBytes the amount of bytes read so far. */ void updateProgress(long readBytes) { _totalBytesRead += readBytes; } }
2,291
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Tar.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/type/Tar.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm.type; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorOutputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.gzipper.java.application.algorithm.ArchivingAlgorithm; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Represents the TAR archive type. * * @author Matthias Fussenegger */ public class Tar extends ArchivingAlgorithm { /** * Constructs a new instance of this class using the TAR constant of * {@link ArchiveStreamFactory} and {@code null}. */ public Tar() { super(ArchiveStreamFactory.TAR, null); } /** * Constructs a new instance of this class using the specified values. * * @param archiveType the archive type, which has to be a constant of * {@link ArchiveStreamFactory}. * @param compressionType the compression type, which has to be a constant * of {@link CompressorStreamFactory}. */ public Tar(String archiveType, String compressionType) { super(archiveType, compressionType); } @Override protected ArchiveOutputStream makeArchiveOutputStream(OutputStream stream) { TarArchiveOutputStream taos = new TarArchiveOutputStream(stream); taos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR); taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); return taos; } @Override protected CompressorOutputStream makeCompressorOutputStream(OutputStream stream) throws IOException { return null; } @Override protected CompressorInputStream makeCompressorInputStream(InputStream stream) throws IOException { return null; } }
2,787
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
TarXz.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/type/TarXz.java
/* * Copyright (C) 2019 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm.type; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorOutputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.apache.commons.compress.compressors.xz.XZCompressorInputStream; import org.apache.commons.compress.compressors.xz.XZCompressorOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Represents the TAR+XZ archive type. * * @author Matthias Fussenegger */ public class TarXz extends Tar { /** * Constructs a new instance of this class using the TAR constant of * {@link ArchiveStreamFactory} and the XZ constant of * {@link CompressorStreamFactory}. */ public TarXz() { super(ArchiveStreamFactory.TAR, CompressorStreamFactory.XZ); } @Override protected CompressorOutputStream makeCompressorOutputStream(OutputStream stream) throws IOException { return new XZCompressorOutputStream(stream); } @Override protected CompressorInputStream makeCompressorInputStream(InputStream stream) throws IOException { return new XZCompressorInputStream(stream); } }
2,028
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z