Java Code Examples for org.apache.poi.util.LittleEndian#getUShort()

The following examples show how to use org.apache.poi.util.LittleEndian#getUShort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PropertySet.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks whether a byte array is in the Horrible Property Set Format.
 *
 * @param src The byte array to check.
 * @param offset The offset in the byte array.
 * @param length The significant number of bytes in the byte
 * array. Only this number of bytes will be checked.
 * @return {@code true} if the byte array is a property set
 * stream, {@code false} if not.
 */
public static boolean isPropertySetStream(final byte[] src, final int offset, final int length) {
    /* FIXME (3): Ensure that at most "length" bytes are read. */

    /*
     * Read the header fields of the stream. They must always be
     * there.
     */
    int o = offset;
    final int byteOrder = LittleEndian.getUShort(src, o);
    o += LittleEndianConsts.SHORT_SIZE;
    if (byteOrder != BYTE_ORDER_ASSERTION) {
        return false;
    }
    final int format = LittleEndian.getUShort(src, o);
    o += LittleEndianConsts.SHORT_SIZE;
    if (format != FORMAT_ASSERTION) {
        return false;
    }
    // final long osVersion = LittleEndian.getUInt(src, offset);
    o += LittleEndianConsts.INT_SIZE;
    // final ClassID classID = new ClassID(src, offset);
    o += ClassID.LENGTH;
    final long sectionCount = LittleEndian.getUInt(src, o);
    return (sectionCount >= 0);
}
 
Example 2
Source File: Formula.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the locator for the corresponding {@link org.apache.poi.hssf.record.SharedFormulaRecord},
    * {@link org.apache.poi.hssf.record.ArrayRecord} or {@link org.apache.poi.hssf.record.TableRecord}
    * if this formula belongs to such a grouping.  The {@link CellReference}
 * returned by this method will  match the top left corner of the range of that grouping.
 * The return value is usually not the same as the location of the cell containing this formula.
 *
 * @return the firstRow & firstColumn of an array formula or shared formula that this formula
 * belongs to.  <code>null</code> if this formula is not part of an array or shared formula.
 */
public CellReference getExpReference() {
	byte[] data = _byteEncoding;
	if (data.length != 5) {
		// tExp and tTbl are always 5 bytes long, and the only ptg in the formula
		return null;
	}
	switch (data[0]) {
		case ExpPtg.sid:
			break;
		case TblPtg.sid:
			break;
		default:
			return null;
	}
	int firstRow = LittleEndian.getUShort(data, 1);
	int firstColumn = LittleEndian.getUShort(data, 3);
	return new CellReference(firstRow, firstColumn);
}
 
Example 3
Source File: ImageHeaderWMF.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public ImageHeaderWMF(byte[] data, final int off) {
    int offset = off;
    int key = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; //header key
    if (key != APMHEADER_KEY) {
        LOG.log(POILogger.WARN, "WMF file doesn't contain a placeable header - ignore parsing");
        handle = 0;
        left = 0;
        top = 0;
        right = 200;
        bottom = 200;
        inch = Units.POINT_DPI; //default resolution is 72 dpi
        reserved = 0;
        return;
    }

    handle = LittleEndian.getUShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    left = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    top = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    right = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    bottom = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE;

    inch = LittleEndian.getUShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    reserved = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE;

    checksum = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    if (checksum != getChecksum()){
        LOG.log(POILogger.WARN, "WMF checksum does not match the header data");
    }
}
 
Example 4
Source File: NDocumentInputStream.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int readUShort() {
	checkAvaliable(SIZE_SHORT);
     byte[] data = new byte[SIZE_SHORT];
     readFully(data, 0, SIZE_SHORT);
     return LittleEndian.getUShort(data);
}
 
Example 5
Source File: XORDecryptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean verifyPassword(String password) {
    XOREncryptionVerifier ver = (XOREncryptionVerifier)getEncryptionInfo().getVerifier();
    int keyVer = LittleEndian.getUShort(ver.getEncryptedKey());
    int verifierVer = LittleEndian.getUShort(ver.getEncryptedVerifier());
    int keyComp      = CryptoFunctions.createXorKey1(password);
    int verifierComp = CryptoFunctions.createXorVerifier1(password);
    if (keyVer == keyComp && verifierVer == verifierComp) {
        byte xorArray[] = CryptoFunctions.createXorArray1(password);
        setSecretKey(new SecretKeySpec(xorArray, "XOR"));
        return true;
    } else {
        return false;
    }
}
 
Example 6
Source File: Biff8DecryptingStream.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reads an unsigned short value without decrypting
 */
@Override
   public int readRecordSID() {
    readPlain(buffer, 0, LittleEndianConsts.SHORT_SIZE);
	int sid = LittleEndian.getUShort(buffer, 0);
	shouldSkipEncryptionOnCurrentRecord = isNeverEncryptedRecord(sid);
	return sid;
}
 
Example 7
Source File: Biff8DecryptingStream.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reads an unsigned short value without decrypting
 */
@Override
   public int readDataSize() {
       readPlain(buffer, 0, LittleEndianConsts.SHORT_SIZE);
       int dataSize = LittleEndian.getUShort(buffer, 0);
       ccis.setNextRecordSize(dataSize);
	return dataSize;
}
 
Example 8
Source File: EscherColorRef.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public EscherColorRef(byte[] source, int start, int len) {
    assert(len == 4 || len == 6);
    
    int offset = start;
    if (len == 6) {
        opid = LittleEndian.getUShort(source, offset);
        offset += 2;
    }
    colorRef = LittleEndian.getInt(source, offset);
}
 
Example 9
Source File: PropertySet.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Initializes this {@link PropertySet} instance from a byte
 * array. The method assumes that it has been checked already that
 * the byte array indeed represents a property set stream. It does
 * no more checks on its own.
 *
 * @param src Byte array containing the property set stream
 * @param offset The property set stream starts at this offset
 * from the beginning of {@code src}
 * @param length Length of the property set stream.
 * @throws UnsupportedEncodingException if HPSF does not (yet) support the
 * property set's character encoding.
 */
private void init(final byte[] src, final int offset, final int length)
throws UnsupportedEncodingException {
    /* FIXME (3): Ensure that at most "length" bytes are read. */
    
    /*
     * Read the stream's header fields.
     */
    int o = offset;
    byteOrder = LittleEndian.getUShort(src, o);
    o += LittleEndianConsts.SHORT_SIZE;
    format = LittleEndian.getUShort(src, o);
    o += LittleEndianConsts.SHORT_SIZE;
    osVersion = (int) LittleEndian.getUInt(src, o);
    o += LittleEndianConsts.INT_SIZE;
    classID = new ClassID(src, o);
    o += ClassID.LENGTH;
    final int sectionCount = LittleEndian.getInt(src, o);
    o += LittleEndianConsts.INT_SIZE;
    if (sectionCount < 0) {
        throw new HPSFRuntimeException("Section count " + sectionCount + " is negative.");
    }

    /*
     * Read the sections, which are following the header. They
     * start with an array of section descriptions. Each one
     * consists of a format ID telling what the section contains
     * and an offset telling how many bytes from the start of the
     * stream the section begins.
     * 
     * Most property sets have only one section. The Document
     * Summary Information stream has 2. Everything else is a rare
     * exception and is no longer fostered by Microsoft.
     */

    /*
     * Loop over the section descriptor array. Each descriptor
     * consists of a ClassID and a DWord, and we have to increment
     * "offset" accordingly.
     */
    for (int i = 0; i < sectionCount; i++) {
        final Section s = new MutableSection(src, o);
        o += ClassID.LENGTH + LittleEndianConsts.INT_SIZE;
        sections.add(s);
    }
}
 
Example 10
Source File: HSSFWorkbook.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("resource")
protected void encryptBytes(byte buf[]) {
    EncryptionInfo ei = getEncryptionInfo();
    if (ei == null) {
        return;
    }
    Encryptor enc = ei.getEncryptor();
    int initialOffset = 0;
    LittleEndianByteArrayInputStream plain = new LittleEndianByteArrayInputStream(buf, 0); // NOSONAR
    LittleEndianByteArrayOutputStream leos = new LittleEndianByteArrayOutputStream(buf, 0); // NOSONAR
    enc.setChunkSize(Biff8DecryptingStream.RC4_REKEYING_INTERVAL);
    byte tmp[] = new byte[1024];
    try {
        ChunkedCipherOutputStream os = enc.getDataStream(leos, initialOffset);
        int totalBytes = 0;
        while (totalBytes < buf.length) {
            plain.read(tmp, 0, 4);
            final int sid = LittleEndian.getUShort(tmp, 0);
            final int len = LittleEndian.getUShort(tmp, 2);
            boolean isPlain = Biff8DecryptingStream.isNeverEncryptedRecord(sid);
            os.setNextRecordSize(len, isPlain);
            os.writePlain(tmp, 0, 4);
            if (sid == BoundSheetRecord.sid) {
                // special case for the field_1_position_of_BOF (=lbPlyPos) field of
                // the BoundSheet8 record which must be unencrypted
                byte bsrBuf[] = new byte[len];
                plain.readFully(bsrBuf);
                os.writePlain(bsrBuf, 0, 4);
                os.write(bsrBuf, 4, len-4);
            } else {
                int todo = len;
                while (todo > 0) {
                    int nextLen = Math.min(todo, tmp.length);
                    plain.readFully(tmp, 0, nextLen);
                    if (isPlain) {
                        os.writePlain(tmp, 0, nextLen);
                    } else {
                        os.write(tmp, 0, nextLen);
                    }
                    todo -= nextLen;
                }
            }
            totalBytes += 4 + len;
        }
        os.close();
    } catch (Exception e) {
        throw new EncryptedDocumentException(e);
    }
}
 
Example 11
Source File: DConRefRecord.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Read constructor.
 *
 * @param data byte array containing a DConRef Record, including the header.
 */
public DConRefRecord(byte[] data)
{
    int offset = 0;
    if (!(LittleEndian.getShort(data, offset) == DConRefRecord.sid))
        throw new RecordFormatException("incompatible sid.");
    offset += LittleEndian.SHORT_SIZE;

    //length = LittleEndian.getShort(data, offset);
    offset += LittleEndian.SHORT_SIZE;

    firstRow = LittleEndian.getUShort(data, offset);
    offset += LittleEndian.SHORT_SIZE;
    lastRow = LittleEndian.getUShort(data, offset);
    offset += LittleEndian.SHORT_SIZE;
    firstCol = LittleEndian.getUByte(data, offset);
    offset += LittleEndian.BYTE_SIZE;
    lastCol = LittleEndian.getUByte(data, offset);
    offset += LittleEndian.BYTE_SIZE;
    charCount = LittleEndian.getUShort(data, offset);
    offset += LittleEndian.SHORT_SIZE;
    if (charCount < 2)
        throw new RecordFormatException("Character count must be >= 2");

    charType = LittleEndian.getUByte(data, offset);
    offset += LittleEndian.BYTE_SIZE; //7 bits reserved + 1 bit type

    /*
     * bytelength is the length of the string in bytes, which depends on whether the string is
     * made of single- or double-byte chars. This is given by charType, which equals 0 if
     * single-byte, 1 if double-byte.
     */
    int byteLength = charCount * ((charType & 1) + 1);

    path = LittleEndian.getByteArray(data, offset, byteLength);
    offset += byteLength;

    /*
     * If it's a self reference, the last one or two bytes (depending on char type) are the
     * unused field. Not sure If i need to bother with this...
     */
    if (path[0] == 0x02)
        _unused = LittleEndian.getByteArray(data, offset, (charType + 1));

}
 
Example 12
Source File: ObjRecord.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ObjRecord(RecordInputStream in) {
	// TODO - problems with OBJ sub-records stream
	// MS spec says first sub-record is always CommonObjectDataSubRecord,
	// and last is always EndSubRecord. OOO spec does not mention ObjRecord(0x005D).
	// Existing POI test data seems to violate that rule. Some test data
	// seems to contain garbage, and a crash is only averted by stopping at
               // what looks like the 'EndSubRecord'

	// Check if this can be continued, if so then the
	// following wont work properly
	byte[] subRecordData = in.readRemainder();
	if (LittleEndian.getUShort(subRecordData, 0) != CommonObjectDataSubRecord.sid) {
		// seems to occur in just one junit on "OddStyleRecord.xls" (file created by CrystalReports)
		// Excel tolerates the funny ObjRecord, and replaces it with a corrected version
		// The exact logic/reasoning is not yet understood
		_uninterpretedData = subRecordData;
		subrecords = null;
		return;
	}

       //YK: files produced by OO violate the condition below
       /*
       if (subRecordData.length % 2 != 0) {
		String msg = "Unexpected length of subRecordData : " + HexDump.toHex(subRecordData);
		throw new RecordFormatException(msg);
	}
       */

	subrecords = new ArrayList<SubRecord>();
	ByteArrayInputStream bais = new ByteArrayInputStream(subRecordData);
	LittleEndianInputStream subRecStream = new LittleEndianInputStream(bais);
	CommonObjectDataSubRecord cmo = (CommonObjectDataSubRecord)SubRecord.createSubRecord(subRecStream, 0);
       subrecords.add(cmo);
       while (true) {
		SubRecord subRecord = SubRecord.createSubRecord(subRecStream, cmo.getObjectType());
		subrecords.add(subRecord);
		if (subRecord.isTerminating()) {
			break;
		}
	}
	int nRemainingBytes = bais.available();
	if (nRemainingBytes > 0) {
		// At present (Oct-2008), most unit test samples have (subRecordData.length % 2 == 0)
		_isPaddedToQuadByteMultiple = subRecordData.length % MAX_PAD_ALIGNMENT == 0;
		if (nRemainingBytes >= (_isPaddedToQuadByteMultiple ? MAX_PAD_ALIGNMENT : NORMAL_PAD_ALIGNMENT)) {
			if (!canPaddingBeDiscarded(subRecordData, nRemainingBytes)) {
				String msg = "Leftover " + nRemainingBytes 
					+ " bytes in subrecord data " + HexDump.toHex(subRecordData);
				throw new RecordFormatException(msg);
			}
			_isPaddedToQuadByteMultiple = false;
		}

       } else {
		_isPaddedToQuadByteMultiple = false;
	}
	_uninterpretedData = null;
}
 
Example 13
Source File: EscherArrayProperty.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public int getNumberOfElementsInArray() {
    return (emptyComplexPart) ? 0 : LittleEndian.getUShort(getComplexData(), 0);
}
 
Example 14
Source File: EscherArrayProperty.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public int getNumberOfElementsInMemory() {
    return (emptyComplexPart) ? 0 : LittleEndian.getUShort(getComplexData(), 2);
}