org.apache.poi.util.StringUtil Java Examples

The following examples show how to use org.apache.poi.util.StringUtil. 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: ConstantValueParser.java    From lams with GNU General Public License v2.0 7 votes vote down vote up
private static Object readAConstantValue(LittleEndianInput in) {
	byte grbit = in.readByte();
	switch(grbit) {
		case TYPE_EMPTY:
			in.readLong(); // 8 byte 'not used' field
			return EMPTY_REPRESENTATION; 
		case TYPE_NUMBER:
			return new Double(in.readDouble());
		case TYPE_STRING:
			return StringUtil.readUnicodeString(in);
		case TYPE_BOOLEAN:
			return readBoolean(in);
		case TYPE_ERROR_CODE:
			int errCode = in.readUShort();
			// next 6 bytes are unused
			in.readUShort();
			in.readInt();
			return ErrorConstant.valueOf(errCode);
	}
	throw new RuntimeException("Unknown grbit value (" + grbit + ")");
}
 
Example #2
Source File: ExtendedPivotTableViewFieldsRecord.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void serialize(LittleEndianOutput out) {

	out.writeInt(_grbit1);
	out.writeByte(_grbit2);
	out.writeByte(_citmShow);
	out.writeShort(_isxdiSort);
	out.writeShort(_isxdiShow);

	if (_subtotalName == null) {
		out.writeShort(STRING_NOT_PRESENT_LEN);
	} else {
		out.writeShort(_subtotalName.length());
	}

	out.writeInt(_reserved1);
	out.writeInt(_reserved2);
	if (_subtotalName != null) {
		StringUtil.putUnicodeLE(_subtotalName, out);
	}
}
 
Example #3
Source File: DataSpaceMapUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static String readUnicodeLPP4(LittleEndianInput is) {
    int length = is.readInt();
    if (length%2 != 0) {
        throw new EncryptedDocumentException(
            "UNICODE-LP-P4 structure is a multiple of 4 bytes. "
            + "If Padding is present, it MUST be exactly 2 bytes long");
    }
    
    String result = StringUtil.readUnicodeLE(is, length/2);
    if (length%4==2) {
        // Padding (variable): A set of bytes that MUST be of the correct size such that the size of the 
        // UNICODE-LP-P4 structure is a multiple of 4 bytes. If Padding is present, it MUST be exactly 
        // 2 bytes long, and each byte MUST be 0x00.            
        is.readShort();
    }
    
    return result;
}
 
Example #4
Source File: StandardEncryptionHeader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * serializes the header 
 */
@Override
public void write(LittleEndianByteArrayOutputStream bos) {
    int startIdx = bos.getWriteIndex();
    LittleEndianOutput sizeOutput = bos.createDelayedOutput(LittleEndianConsts.INT_SIZE);
    bos.writeInt(getFlags());
    bos.writeInt(0); // size extra
    bos.writeInt(getCipherAlgorithm().ecmaId);
    bos.writeInt(getHashAlgorithm().ecmaId);
    bos.writeInt(getKeySize());
    bos.writeInt(getCipherProvider().ecmaId);
    bos.writeInt(0); // reserved1
    bos.writeInt(0); // reserved2
    String cspName = getCspName();
    if (cspName == null) {
        cspName = getCipherProvider().cipherProviderName;
    }
    bos.write(StringUtil.getToUnicodeLE(cspName));
    bos.writeShort(0);
    int headerSize = bos.getWriteIndex()-startIdx-LittleEndianConsts.INT_SIZE;
    sizeOutput.writeInt(headerSize);        
}
 
Example #5
Source File: BinaryRC4Decryptor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected static SecretKey generateSecretKey(String password, EncryptionVerifier ver) {
    if (password.length() > 255) {
        password = password.substring(0, 255);
    }
    HashAlgorithm hashAlgo = ver.getHashAlgorithm();
    MessageDigest hashAlg = CryptoFunctions.getMessageDigest(hashAlgo);
    byte hash[] = hashAlg.digest(StringUtil.getToUnicodeLE(password));
    byte salt[] = ver.getSalt();
    hashAlg.reset();
    for (int i = 0; i < 16; i++) {
        hashAlg.update(hash, 0, 5);
        hashAlg.update(salt);
    }

    hash = new byte[5];
    System.arraycopy(hashAlg.digest(), 0, hash, 0, 5);
    SecretKey skey = new SecretKeySpec(hash, ver.getCipherAlgorithm().jceId);
    return skey;
}
 
Example #6
Source File: HSSFPatriarch.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Does this HSSFPatriarch contain a chart?
 * (Technically a reference to a chart, since they
 * get stored in a different block of records)
 * FIXME - detect chart in all cases (only seems
 * to work on some charts so far)
 */
public boolean containsChart() {
    // TODO - support charts properly in usermodel

    // We're looking for a EscherOptRecord
    EscherOptRecord optRecord = (EscherOptRecord)
            _boundAggregate.findFirstWithId(EscherOptRecord.RECORD_ID);
    if (optRecord == null) {
        // No opt record, can't have chart
        return false;
    }

    for (Iterator<EscherProperty> it = optRecord.getEscherProperties().iterator(); it.hasNext(); ) {
        EscherProperty prop = it.next();
        if (prop.getPropertyNumber() == 896 && prop.isComplex()) {
            EscherComplexProperty cp = (EscherComplexProperty) prop;
            String str = StringUtil.getFromUnicodeLE(cp.getComplexData());

            if (str.equals("Chart 1\0")) {
                return true;
            }
        }
    }

    return false;
}
 
Example #7
Source File: StyleRecord.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void serialize(LittleEndianOutput out) {
	out.writeShort(field_1_xf_index);
	if (isBuiltin()) {
		out.writeByte(field_2_builtin_style);
		out.writeByte(field_3_outline_style_level);
	} else {
		out.writeShort(field_4_name.length());
		out.writeByte(field_3_stringHasMultibyte ? 0x01 : 0x00);
		if (field_3_stringHasMultibyte) {
			StringUtil.putUnicodeLE(getName(), out);
		} else {
			StringUtil.putCompressedUnicode(getName(), out);
		}
	}
}
 
Example #8
Source File: DConRefRecord.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @return the link's path, with the special characters stripped/replaced. May be null.
 * See MS-XLS 2.5.277 (VirtualPath)
 */
public String getReadablePath()
{
    if (path != null)
    {
        //all of the path strings start with either 0x02 or 0x01 followed by zero or
        //more of 0x01..0x08
        int offset = 1;
        while (path[offset] < 0x20 && offset < path.length)
        {
            offset++;
        }
        String out = new String(Arrays.copyOfRange(path, offset, path.length), StringUtil.UTF8);
        //UNC paths have \u0003 chars as path separators.
        out = out.replaceAll("\u0003", "/");
        return out;
    }
    return null;
}
 
Example #9
Source File: ExternalNameRecord.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected int getDataSize(){
	int result = 2 + 4;  // short and int
       result += StringUtil.getEncodedSize(field_4_name) - 1; //size is byte, not short 

       if(!isOLELink() && !isStdDocumentNameIdentifier()){
           if(isAutomaticLink()){
           	if(_ddeValues != null) {
                   result += 3; // byte, short
                   result += ConstantValueParser.getEncodedSize(_ddeValues);
           	}
           } else {
               result += field_5_name_definition.getEncodedSize();
           }
       }
	return result;
}
 
Example #10
Source File: ExternalNameRecord.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void serialize(LittleEndianOutput out) {
	out.writeShort(field_1_option_flag);
	out.writeShort(field_2_ixals);
	out.writeShort(field_3_not_used);

	out.writeByte(field_4_name.length());
	StringUtil.writeUnicodeStringFlagAndData(out, field_4_name);

       if(!isOLELink() && !isStdDocumentNameIdentifier()){
           if(isAutomaticLink()){
           	if(_ddeValues != null) {
                   out.writeByte(_nColumns-1);
                   out.writeShort(_nRows-1);
                   ConstantValueParser.encode(out, _ddeValues);
           	}
           } else {
               field_5_name_definition.serialize(out);
           }
       }
}
 
Example #11
Source File: NoteRecord.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Read the record data from the supplied <code>RecordInputStream</code>
 * 
 * @param in the RecordInputStream to read from
 */
public NoteRecord(RecordInputStream in) {
	field_1_row = in.readUShort();
	field_2_col = in.readShort();
	field_3_flags = in.readShort();
	field_4_shapeid = in.readUShort();
	int length = in.readShort();
	field_5_hasMultibyte = in.readByte() != 0x00;
	if (field_5_hasMultibyte) {
		field_6_author = StringUtil.readUnicodeLE(in, length);
	} else {
		field_6_author = StringUtil.readCompressedUnicode(in, length);
	}
		if (in.available() == 1) {
		field_7_padding = Byte.valueOf(in.readByte());
	} else if (in.available() == 2 && length == 0) {
	    // If there's no author, may be double padded
           field_7_padding = Byte.valueOf(in.readByte());
           in.readByte();
		}
}
 
Example #12
Source File: NoteRecord.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void serialize(LittleEndianOutput out) {
	out.writeShort(field_1_row);
	out.writeShort(field_2_col);
	out.writeShort(field_3_flags);
	out.writeShort(field_4_shapeid);
	out.writeShort(field_6_author.length());
	out.writeByte(field_5_hasMultibyte ? 0x01 : 0x00);
	if (field_5_hasMultibyte) {
		StringUtil.putUnicodeLE(field_6_author, out);
	} else {
		StringUtil.putCompressedUnicode(field_6_author, out);
	}
	if (field_7_padding != null) {
		out.writeByte(field_7_padding.intValue());
	}
}
 
Example #13
Source File: FontRecord.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void serialize(LittleEndianOutput out) {

		out.writeShort(getFontHeight());
		out.writeShort(getAttributes());
		out.writeShort(getColorPaletteIndex());
		out.writeShort(getBoldWeight());
		out.writeShort(getSuperSubScript());
		out.writeByte(getUnderline());
		out.writeByte(getFamily());
		out.writeByte(getCharset());
		out.writeByte(field_9_zero);
		int fontNameLen = field_11_font_name.length();
		out.writeByte(fontNameLen);
		boolean hasMultibyte = StringUtil.hasMultibyte(field_11_font_name);
		out.writeByte(hasMultibyte ? 0x01 : 0x00);
		if (fontNameLen > 0) {
			if (hasMultibyte) {
			   StringUtil.putUnicodeLE(field_11_font_name, out);
			} else {
				StringUtil.putCompressedUnicode(field_11_font_name, out);
			}
		}
	}
 
Example #14
Source File: NameCommentRecord.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void serialize(final LittleEndianOutput out) {
  final int field_4_name_length = field_6_name_text.length();
  final int field_5_comment_length = field_7_comment_text.length();

  out.writeShort(field_1_record_type);
  out.writeShort(field_2_frt_cell_ref_flag);
  out.writeLong(field_3_reserved);
  out.writeShort(field_4_name_length);
  out.writeShort(field_5_comment_length);

  boolean isNameMultiByte = StringUtil.hasMultibyte(field_6_name_text);
  out.writeByte(isNameMultiByte ? 1 : 0);
  if (isNameMultiByte) {
      StringUtil.putUnicodeLE(field_6_name_text, out);
  } else {
      StringUtil.putCompressedUnicode(field_6_name_text, out);
  }
  boolean isCommentMultiByte = StringUtil.hasMultibyte(field_7_comment_text);
  out.writeByte(isCommentMultiByte ? 1 : 0);
  if (isCommentMultiByte) {
      StringUtil.putUnicodeLE(field_7_comment_text, out);
  } else {
      StringUtil.putCompressedUnicode(field_7_comment_text, out);
  }
}
 
Example #15
Source File: NameCommentRecord.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param ris the RecordInputstream to read the record from
 */
public NameCommentRecord(final RecordInputStream ris) {
  final LittleEndianInput in = ris;
  field_1_record_type = in.readShort();
  field_2_frt_cell_ref_flag = in.readShort();
  field_3_reserved = in.readLong();
  final int field_4_name_length = in.readShort();
  final int field_5_comment_length = in.readShort();

  if (in.readByte() == 0) {
      field_6_name_text = StringUtil.readCompressedUnicode(in, field_4_name_length);
  } else {
      field_6_name_text = StringUtil.readUnicodeLE(in, field_4_name_length);
  }
  if (in.readByte() == 0) {
      field_7_comment_text = StringUtil.readCompressedUnicode(in, field_5_comment_length);
  } else {
      field_7_comment_text = StringUtil.readUnicodeLE(in, field_5_comment_length);
  }    
}
 
Example #16
Source File: UnicodeString.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected void serialize(ContinuableRecordOutput out) {
   int dataSize = getDataSize();
   
   out.writeContinueIfRequired(8);
   out.writeShort(reserved);
   out.writeShort(dataSize);
   out.writeShort(formattingFontIndex);
   out.writeShort(formattingOptions);
   
   out.writeContinueIfRequired(6);
   out.writeShort(numberOfRuns);
   out.writeShort(phoneticText.length());
   out.writeShort(phoneticText.length());
   
   out.writeContinueIfRequired(phoneticText.length()*2);
   StringUtil.putUnicodeLE(phoneticText, out);
   
   for(int i=0; i<phRuns.length; i++) {
      phRuns[i].serialize(out);
   }
   
   out.write(extraData);
}
 
Example #17
Source File: LbsDataSubRecord.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected int getDataSize() {
    int result = 2; // 2 initial shorts

    // optional link formula
    if (_linkPtg != null) {
        result += 2; // encoded Ptg size
        result += 4; // unknown int
        result += _linkPtg.getSize();
        if (_unknownPostFormulaByte != null) {
            result += 1;
        }
    }

    result += 4 * 2; // 4 shorts
    if(_dropData != null) {
        result += _dropData.getDataSize();
    }
    if(_rgLines != null) {
        for(String str : _rgLines){
            result += StringUtil.getEncodedSize(str);
        }
    }
    if(_bsels != null) {
        result += _bsels.length;
    }
    return result;
}
 
Example #18
Source File: HeaderFooterBase.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public final void serialize(LittleEndianOutput out) {
	if (getTextLength() > 0) {
		out.writeShort(getTextLength());
		out.writeByte(field_2_hasMultibyte ? 0x01 : 0x00);
		if (field_2_hasMultibyte) {
			StringUtil.putUnicodeLE(field_3_text, out);
		} else {
			StringUtil.putCompressedUnicode(field_3_text, out);
		}
	}
}
 
Example #19
Source File: LbsDataSubRecord.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void serialize(LittleEndianOutput out) {
    out.writeShort(_wStyle);
    out.writeShort(_cLine);
    out.writeShort(_dxMin);
    StringUtil.writeUnicodeString(out, _str);
    if(_unused != null) {
        out.writeByte(_unused);
    }
}
 
Example #20
Source File: LbsDataSubRecord.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public int getDataSize() {
    int size = 6;
    size += StringUtil.getEncodedSize(_str);
    if(_unused != null) {
        size++;
    }
    return size;
}
 
Example #21
Source File: LbsDataSubRecord.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public LbsDropData(LittleEndianInput in){
    _wStyle = in.readUShort();
    _cLine = in.readUShort();
    _dxMin = in.readUShort();
    _str = StringUtil.readUnicodeString(in);
    if(StringUtil.getEncodedSize(_str) % 2 != 0){
        _unused = in.readByte();
    }
}
 
Example #22
Source File: FontRecord.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected int getDataSize() {
	int size = 16; // 5 shorts + 6 bytes
	int fontNameLen = field_11_font_name.length();
	if (fontNameLen < 1) {
		return size;
	}

	boolean hasMultibyte = StringUtil.hasMultibyte(field_11_font_name);
	return size + fontNameLen * (hasMultibyte ? 2 : 1);
}
 
Example #23
Source File: CryptoAPIDecryptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected static SecretKey generateSecretKey(String password, EncryptionVerifier ver) {
    if (password.length() > 255) {
        password = password.substring(0, 255);
    }
    HashAlgorithm hashAlgo = ver.getHashAlgorithm();
    MessageDigest hashAlg = CryptoFunctions.getMessageDigest(hashAlgo);
    hashAlg.update(ver.getSalt());
    byte hash[] = hashAlg.digest(StringUtil.getToUnicodeLE(password));
    SecretKey skey = new SecretKeySpec(hash, ver.getCipherAlgorithm().jceId);
    return skey;
}
 
Example #24
Source File: DataSpaceMapUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static void writeUnicodeLPP4(LittleEndianOutput os, String string) {
    byte buf[] = StringUtil.getToUnicodeLE(string);
    os.writeInt(buf.length);
    os.write(buf);
    if (buf.length%4==2) {
        os.writeShort(0);
    }
}
 
Example #25
Source File: ExternalNameRecord.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public ExternalNameRecord(RecordInputStream in) {
field_1_option_flag = in.readShort();
field_2_ixals       = in.readShort();
    field_3_not_used    = in.readShort();

      int numChars = in.readUByte();
      field_4_name = StringUtil.readUnicodeString(in, numChars);

      // the record body can take different forms.
      // The form is dictated by the values of 3-th and 4-th bits in field_1_option_flag
      if(!isOLELink() && !isStdDocumentNameIdentifier()){
          // another switch: the fWantAdvise bit specifies whether the body describes
          // an external defined name or a DDE data item
          if(isAutomaticLink()){
              if(in.available() > 0) {
                 //body specifies DDE data item
                 int nColumns = in.readUByte() + 1;
                 int nRows = in.readShort() + 1;
 
                 int totalCount = nRows * nColumns;
                 _ddeValues = ConstantValueParser.parse(in, totalCount);
                 _nColumns = nColumns;
                 _nRows = nRows;
              }
          } else {
              //body specifies an external defined name
              int formulaLen = in.readUShort();
              field_5_name_definition = Formula.read(formulaLen, in);
          }
      }
  }
 
Example #26
Source File: CryptoFunctions.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generalized method for read and write protection hash generation.
 * The difference is, read protection uses the order iterator then hash in the hash loop, whereas write protection
 * uses first the last hash value and then the current iterator value
 *
 * @param password
 * @param hashAlgorithm
 * @param salt
 * @param spinCount
 * @param iteratorFirst if true, the iterator is hashed before the n-1 hash value,
 *        if false the n-1 hash value is applied first
 * @return the hashed password
 */
public static byte[] hashPassword(String password, HashAlgorithm hashAlgorithm, byte salt[], int spinCount, boolean iteratorFirst) {
    // If no password was given, use the default
    if (password == null) {
        password = Decryptor.DEFAULT_PASSWORD;
    }
    
    MessageDigest hashAlg = getMessageDigest(hashAlgorithm);
    
    hashAlg.update(salt);
    byte[] hash = hashAlg.digest(StringUtil.getToUnicodeLE(password));
    byte[] iterator = new byte[LittleEndianConsts.INT_SIZE];

    byte[] first = (iteratorFirst ? iterator : hash);
    byte[] second = (iteratorFirst ? hash : iterator);
    
    try {
        for (int i = 0; i < spinCount; i++) {
            LittleEndian.putInt(iterator, 0, i);
            hashAlg.reset();
            hashAlg.update(first);
            hashAlg.update(second);
            hashAlg.digest(hash, 0, hash.length); // don't create hash buffer everytime new
        }
    } catch (DigestException e) {
        throw new EncryptedDocumentException("error in password hashing");
    }
    
    return hash;
}
 
Example #27
Source File: ConstantValueParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return encoded size without the 'type' code byte
 */
private static int getEncodedSize(Object object) {
	if(object == EMPTY_REPRESENTATION) {
		return 8;
	}
	Class<?> cls = object.getClass();
	
	if(cls == Boolean.class || cls == Double.class || cls == ErrorConstant.class) {
		return 8;
	}
	String strVal = (String)object;
	return StringUtil.getEncodedSize(strVal);
}
 
Example #28
Source File: StringPtg.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** Create a StringPtg from a stream */
public StringPtg(LittleEndianInput in)  {
	int nChars = in.readUByte(); // Note - nChars is 8-bit
	_is16bitUnicode = (in.readByte() & 0x01) != 0;
	if (_is16bitUnicode) {
		field_3_string = StringUtil.readUnicodeLE(in, nChars);
	} else {
		field_3_string = StringUtil.readCompressedUnicode(in, nChars);
	}
}
 
Example #29
Source File: WriteAccessRecord.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * set the username for the user that created the report. HSSF uses the
 * logged in user.
 * 
 * @param username of the user who is logged in (probably "tomcat" or "apache")
 */
public void setUsername(String username) {
	boolean is16bit = StringUtil.hasMultibyte(username);
	int encodedByteCount = 3 + username.length() * (is16bit ? 2 : 1);
	int paddingSize = DATA_SIZE - encodedByteCount;
	if (paddingSize < 0) {
		throw new IllegalArgumentException("Name is too long: " + username);
	}

	field_1_username = username;
}
 
Example #30
Source File: FileSharingRecord.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void serialize(LittleEndianOutput out) {
    // TODO - junit
    out.writeShort(getReadOnly());
    out.writeShort(getPassword());
    out.writeShort(field_3_username_value.length());
    if(field_3_username_value.length() > 0) {
    	out.writeByte(field_3_username_unicode_options);
        StringUtil.putCompressedUnicode(getUsername(), out);
    }
}