下面列出了javax.xml.stream.EventFilter#org.apache.poi.util.POILogger 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Writes a warning to {@code System.err} that a variant type is
* unsupported by HPSF. Such a warning is written only once for each variant
* type. Log messages can be turned on or off by
*
* @param ex The exception to log
*/
protected static void writeUnsupportedTypeMessage
(final UnsupportedVariantTypeException ex) {
if (isLogUnsupportedTypes())
{
if (unsupportedMessage == null) {
unsupportedMessage = new LinkedList<Long>();
}
Long vt = Long.valueOf(ex.getVariantType());
if (!unsupportedMessage.contains(vt))
{
logger.log( POILogger.ERROR, ex.getMessage());
unsupportedMessage.add(vt);
}
}
}
private void checkCodePage(String value) {
int cp = getCodepage();
if (cp == -1) {
cp = Property.DEFAULT_CODEPAGE;
}
if (cp == CodePageUtil.CP_UNICODE) {
return;
}
String cps = "";
try {
cps = CodePageUtil.codepageToEncoding(cp, false);
} catch (UnsupportedEncodingException e) {
LOG.log(POILogger.ERROR, "Codepage '"+cp+"' can't be found.");
}
if (!cps.isEmpty() && Charset.forName(cps).newEncoder().canEncode(value)) {
return;
}
LOG.log(POILogger.DEBUG, "Charset '"+cps+"' can't encode '"+value+"' - switching to unicode.");
setCodepage(CodePageUtil.CP_UNICODE);
}
private CFRecordsAggregate(CFHeaderBase pHeader, CFRuleBase[] pRules) {
if(pHeader == null) {
throw new IllegalArgumentException("header must not be null");
}
if(pRules == null) {
throw new IllegalArgumentException("rules must not be null");
}
if(pRules.length > MAX_97_2003_CONDTIONAL_FORMAT_RULES) {
logger.log(POILogger.WARN, "Excel versions before 2007 require that "
+ "No more than " + MAX_97_2003_CONDTIONAL_FORMAT_RULES
+ " rules may be specified, " + pRules.length + " were found,"
+ " this file will cause problems with old Excel versions");
}
if (pRules.length != pHeader.getNumberOfConditionalFormats()) {
throw new RecordFormatException("Mismatch number of rules");
}
header = pHeader;
rules = new ArrayList<CFRuleBase>(pRules.length);
for (CFRuleBase pRule : pRules) {
checkRuleType(pRule);
rules.add(pRule);
}
}
@Override
public void drawContent(Graphics2D graphics) {
PictureData data = getShape().getPictureData();
if(data == null) return;
Rectangle2D anchor = getAnchor(graphics, getShape());
Insets insets = getShape().getClipping();
try {
ImageRenderer renderer = getImageRenderer(graphics, data.getContentType());
renderer.loadImage(data.getData(), data.getContentType());
renderer.drawImage(graphics, anchor, insets);
} catch (IOException e) {
LOG.log(POILogger.ERROR, "image can't be loaded/rendered.", e);
}
}
/**
* @param stream the stream to be closed
* @param success <code>false</code> if an exception is currently being thrown in the calling method
*/
protected void closeInputStream(InputStream stream, boolean success) {
if(stream.markSupported() && !(stream instanceof ByteArrayInputStream)) {
String msg = "POIFS is closing the supplied input stream of type ("
+ stream.getClass().getName() + ") which supports mark/reset. "
+ "This will be a problem for the caller if the stream will still be used. "
+ "If that is the case the caller should wrap the input stream to avoid this close logic. "
+ "This warning is only temporary and will not be present in future versions of POI.";
_logger.log(POILogger.WARN, msg);
}
try {
stream.close();
} catch (IOException e) {
if(success) {
throw new RuntimeException(e);
}
// else not success? Try block did not complete normally
// just print stack trace and leave original ex to be thrown
_logger.log(POILogger.ERROR, "can't close input stream", e);
}
}
public void draw(Shape shape)
{
if (shape instanceof Line2D)
{
Line2D shape2d = (Line2D) shape;
int width = 0;
if (_stroke != null && _stroke instanceof BasicStroke) {
width = (int) ((BasicStroke)_stroke).getLineWidth() * 12700;
}
drawLine((int)shape2d.getX1(), (int)shape2d.getY1(), (int)shape2d.getX2(), (int)shape2d.getY2(), width);
}
else
{
if (logger.check(POILogger.WARN))
logger.log(POILogger.WARN, "draw not fully supported");
}
}
@Override
public void close() throws IOException {
if (isClosed) {
LOG.log(POILogger.DEBUG, "ChunkedCipherOutputStream was already closed - ignoring");
return;
}
isClosed = true;
try {
writeChunk(false);
super.close();
if (fileOut != null) {
int oleStreamSize = (int)(fileOut.length()+LittleEndianConsts.LONG_SIZE);
calculateChecksum(fileOut, (int)pos);
dir.createDocument(DEFAULT_POIFS_ENTRY, oleStreamSize, new EncryptedPackageWriter());
createEncryptionInfoEntry(dir, fileOut);
}
} catch (GeneralSecurityException e) {
throw new IOException(e);
}
}
@Override
public void processPOIFSWriterEvent(POIFSWriterEvent event) {
try {
LittleEndianOutputStream leos = new LittleEndianOutputStream(event.getStream());
// StreamSize (8 bytes): An unsigned integer that specifies the number of bytes used by data
// encrypted within the EncryptedData field, not including the size of the StreamSize field.
// Note that the actual size of the \EncryptedPackage stream (1) can be larger than this
// value, depending on the block size of the chosen encryption algorithm
leos.writeLong(countBytes);
FileInputStream fis = new FileInputStream(fileOut);
try {
IOUtils.copy(fis, leos);
} finally {
fis.close();
}
if (!fileOut.delete()) {
logger.log(POILogger.ERROR, "Can't delete temporary encryption file: "+fileOut);
}
leos.close();
} catch (IOException e) {
throw new EncryptedDocumentException(e);
}
}
private static void unmap(final ByteBuffer buffer) {
// not necessary for HeapByteBuffer, avoid lots of log-output on this class
if(buffer.getClass().getName().endsWith("HeapByteBuffer")) {
return;
}
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
@SuppressForbidden("Java 9 Jigsaw whitelists access to sun.misc.Cleaner, so setAccessible works")
public Void run() {
try {
final Method getCleanerMethod = buffer.getClass().getMethod("cleaner");
getCleanerMethod.setAccessible(true);
final Object cleaner = getCleanerMethod.invoke(buffer);
if (cleaner != null) {
cleaner.getClass().getMethod("clean").invoke(cleaner);
}
} catch (Exception e) {
logger.log(POILogger.WARN, "Unable to unmap memory mapped ByteBuffer.", e);
}
return null; // Void
}
});
}
/**
* @param in the RecordInputstream to read the record from
*/
public OldLabelRecord(RecordInputStream in)
{
super(in, in.getSid() == biff2_sid);
if (isBiff2()) {
field_4_string_len = (short)in.readUByte();
} else {
field_4_string_len = in.readShort();
}
// Can only decode properly later when you know the codepage
field_5_bytes = new byte[field_4_string_len];
in.read(field_5_bytes, 0, field_4_string_len);
if (in.remaining() > 0) {
logger.log(POILogger.INFO,
"LabelRecord data remains: " + in.remaining() +
" : " + HexDump.toHex(in.readRemainder())
);
}
}
/**
* @param in the RecordInputstream to read the record from
*/
public LabelRecord(RecordInputStream in)
{
field_1_row = in.readUShort();
field_2_column = in.readShort();
field_3_xf_index = in.readShort();
field_4_string_len = in.readShort();
field_5_unicode_flag = in.readByte();
if (field_4_string_len > 0) {
if (isUnCompressedUnicode()) {
field_6_value = in.readUnicodeLEString(field_4_string_len);
} else {
field_6_value = in.readCompressedUnicode(field_4_string_len);
}
} else {
field_6_value = "";
}
if (in.remaining() > 0) {
logger.log(POILogger.INFO,
"LabelRecord data remains: " + in.remaining() +
" : " + HexDump.toHex(in.readRemainder())
);
}
}
/**
* Copies the entries in src to dest, using the preferential data type
* so that maps can be compared for equality
*
* @param src the property map to copy from (read-only)
* @param dest the property map to copy into
* @since POI 3.15 beta 3
*/
private static void putAll(final Map<String, Object> src, Map<String, Object> dest) {
for (final String key : src.keySet()) {
if (shortValues.contains(key)) {
dest.put(key, getShort(src, key));
} else if (booleanValues.contains(key)) {
dest.put(key, getBoolean(src, key));
} else if (borderTypeValues.contains(key)) {
dest.put(key, getBorderStyle(src, key));
} else if (ALIGNMENT.equals(key)) {
dest.put(key, getHorizontalAlignment(src, key));
} else if (VERTICAL_ALIGNMENT.equals(key)) {
dest.put(key, getVerticalAlignment(src, key));
} else if (FILL_PATTERN.equals(key)) {
dest.put(key, getFillPattern(src, key));
} else {
if (log.check(POILogger.INFO)) {
log.log(POILogger.INFO, "Ignoring unrecognized CellUtil format properties key: " + key);
}
}
}
}
@SuppressWarnings("unchecked")
private <T> T readPropertySet(Class<T> clazz, String name) {
String localName = clazz.getName().substring(clazz.getName().lastIndexOf('.')+1);
try {
PropertySet ps = getPropertySet(name);
if (clazz.isInstance(ps)) {
return (T)ps;
} else if (ps != null) {
logger.log(POILogger.WARN, localName+" property set came back with wrong class - "+ps.getClass().getName());
} else {
logger.log(POILogger.WARN, localName+" property set came back as null");
}
} catch (IOException e) {
logger.log(POILogger.ERROR, "can't retrieve property set", e);
}
return null;
}
/**
* Adds a value record to the sheet's contained binary records
* (i.e. LabelSSTRecord or NumberRecord).
* <P>
* This method is "loc" sensitive. Meaning you need to set LOC to where you
* want it to start searching. If you don't know do this: setLoc(getDimsLoc).
* When adding several rows you can just start at the last one by leaving loc
* at what this sets it to.
*
* @param row the row to add the cell value to
* @param col the cell value record itself.
*/
public void addValueRecord(int row, CellValueRecordInterface col) {
if(log.check(POILogger.DEBUG)) {
log.log(POILogger.DEBUG, "add value record row" + row);
}
DimensionsRecord d = _dimensions;
if (col.getColumn() >= d.getLastCol()) {
d.setLastCol(( short ) (col.getColumn() + 1));
}
if (col.getColumn() < d.getFirstCol()) {
d.setFirstCol(col.getColumn());
}
_rowsAggregate.insertCell(col);
}
/**
* Decompresses the provided data, returning the inflated result.
*
* @param data the deflated picture data.
* @return the inflated picture data.
*/
private static byte[] inflatePictureData(byte[] data) {
try {
InflaterInputStream in = new InflaterInputStream(
new ByteArrayInputStream( data ) );
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
int readBytes;
while ((readBytes = in.read(buf)) > 0) {
out.write(buf, 0, readBytes);
}
return out.toByteArray();
} catch (IOException e) {
log.log(POILogger.WARN, "Possibly corrupt compression or non-compressed data", e);
return data;
}
}
private Format createNumberFormat(String formatStr, double cellValue) {
String format = cleanFormatForNumber(formatStr);
DecimalFormatSymbols symbols = decimalSymbols;
// Do we need to change the grouping character?
// eg for a format like #'##0 which wants 12'345 not 12,345
Matcher agm = alternateGrouping.matcher(format);
if (agm.find()) {
char grouping = agm.group(2).charAt(0);
// Only replace the grouping character if it is not the default
// grouping character for the US locale (',') in order to enable
// correct grouping for non-US locales.
if (grouping != ',') {
symbols = DecimalFormatSymbols.getInstance(locale);
symbols.setGroupingSeparator(grouping);
String oldPart = agm.group(1);
String newPart = oldPart.replace(grouping, ',');
format = format.replace(oldPart, newPart);
}
}
try {
return new InternalDecimalFormatWithScale(format, symbols);
} catch (IllegalArgumentException iae) {
logger.log(POILogger.DEBUG, "Formatting failed for format " + formatStr + ", falling back", iae);
// the pattern could not be parsed correctly,
// so fall back to the default number format
return getDefaultFormat(cellValue);
}
}
void read( LittleEndianByteArrayInputStream lei ) {
int offset = lei.getReadIndex();
int size = lei.readInt();
_value = new byte[size];
if (size == 0) {
return;
}
// If Size is zero, this field MUST be zero bytes in length. If Size is
// nonzero and the CodePage property set's CodePage property has the value CP_WINUNICODE
// (0x04B0), then the value MUST be a null-terminated array of 16-bit Unicode characters,
// followed by zero padding to a multiple of 4 bytes. If Size is nonzero and the property set's
// CodePage property has any other value, it MUST be a null-terminated array of 8-bit characters
// from the code page identified by the CodePage property, followed by zero padding to a
// multiple of 4 bytes. The string represented by this field MAY contain embedded or additional
// trailing null characters and an OLEPS implementation MUST be able to handle such strings.
lei.readFully(_value);
if (_value[size - 1] != 0 ) {
// TODO Some files, such as TestVisioWithCodepage.vsd, are currently
// triggering this for values that don't look like codepages
// See Bug #52258 for details
String msg = "CodePageString started at offset #" + offset + " is not NULL-terminated";
LOG.log(POILogger.WARN, msg);
}
TypedPropertyValue.skipPadding(lei);
}
void read( LittleEndianByteArrayInputStream lei ) {
short value = lei.readShort();
switch (value) {
case 0:
_value = false;
break;
case -1:
_value = true;
break;
default:
LOG.log( POILogger.WARN, "VARIANT_BOOL value '"+value+"' is incorrect" );
_value = true;
break;
}
}
private String decodeValueFromID() {
try {
switch((int)getID()) {
case PropertyIDMap.PID_CODEPAGE:
return CodePageUtil.codepageToEncoding(((Number)value).intValue());
case PropertyIDMap.PID_LOCALE:
return LocaleUtil.getLocaleFromLCID(((Number)value).intValue());
}
} catch (Exception e) {
LOG.log(POILogger.WARN, "Can't decode id "+getID());
}
return null;
}
/**
* Return the blip signature
*
* @return the blip signature
*/
public short getSignature() {
switch (getRecordId()) {
case RECORD_ID_EMF: return HSSFPictureData.MSOBI_EMF;
case RECORD_ID_WMF: return HSSFPictureData.MSOBI_WMF;
case RECORD_ID_PICT: return HSSFPictureData.MSOBI_PICT;
}
if (log.check(POILogger.WARN)) {
log.log(POILogger.WARN, "Unknown metafile: " + getRecordId());
}
return 0;
}
private static Class<?> getOOXMLClass() {
try {
return OLE2ExtractorFactory.class.getClassLoader().loadClass(
"org.apache.poi.extractor.ExtractorFactory"
);
} catch (ClassNotFoundException e) {
LOGGER.log(POILogger.WARN, "POI OOXML jar missing");
return null;
}
}
private static Class<?> getScratchpadClass() {
try {
return OLE2ExtractorFactory.class.getClassLoader().loadClass(
"org.apache.poi.extractor.OLE2ScratchpadExtractorFactory"
);
} catch (ClassNotFoundException e) {
LOGGER.log(POILogger.ERROR, "POI Scratchpad jar missing");
throw new IllegalStateException("POI Scratchpad jar missing, required for ExtractorFactory");
}
}
/**
* Returns the index of the format string, used by your cell, or -1 if none found
*
* @param cell the cell
*
* @return the index of the format string
*/
public int getFormatIndex(CellValueRecordInterface cell) {
ExtendedFormatRecord xfr = _xfRecords.get(cell.getXFIndex());
if (xfr == null) {
logger.log( POILogger.ERROR, "Cell " + cell.getRow() + "," + cell.getColumn()
+ " uses XF with index " + cell.getXFIndex() + ", but we don't have that");
return -1;
}
return xfr.getFormatIndex();
}
/**
* Returns the current <code>Composite</code> in the
* <code>Graphics2D</code> context.
* @return the current <code>Graphics2D</code> <code>Composite</code>,
* which defines a compositing style.
* @see #setComposite
*/
@NotImplemented
public Composite getComposite(){
if (log.check(POILogger.WARN)) {
log.log(POILogger.WARN, "Not implemented");
}
return null;
}
@SuppressWarnings("unused")
public void init(InputStream is) throws XMLStreamException, JAXBException {
// StAX:
EventFilter startElementFilter = new EventFilter() {
@Override
public boolean accept(XMLEvent event) {
return event.isStartElement();
}
};
XMLInputFactory staxFactory = StaxHelper.newXMLInputFactory();
XMLEventReader staxReader = staxFactory.createXMLEventReader(is);
XMLEventReader staxFiltRd = staxFactory.createFilteredReader(staxReader, startElementFilter);
// ignore StartElement:
/* XMLEvent evDoc = */ staxFiltRd.nextEvent();
// JAXB:
JAXBContext jaxbContext = JAXBContext.newInstance(BINDING_PACKAGE);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
long cntElem = 0;
while (staxFiltRd.peek() != null) {
StartElement evRoot = (StartElement)staxFiltRd.peek();
String name = evRoot.getName().getLocalPart();
JAXBElement<CTCustomGeometry2D> el = unmarshaller.unmarshal(staxReader, CTCustomGeometry2D.class);
CTCustomGeometry2D cus = el.getValue();
cntElem++;
if(containsKey(name)) {
LOG.log(POILogger.WARN, "Duplicate definition of " + name);
}
put(name, new CustomGeometry(cus));
}
}
/**
* Convert a single CustomGeometry object, i.e. from xmlbeans
*/
public static CustomGeometry convertCustomGeometry(XMLStreamReader staxReader) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(BINDING_PACKAGE);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<CTCustomGeometry2D> el = unmarshaller.unmarshal(staxReader, CTCustomGeometry2D.class);
return new CustomGeometry(el.getValue());
} catch (JAXBException e) {
LOG.log(POILogger.ERROR, "Unable to parse single custom geometry", e);
return null;
}
}
public ImageHeaderBitmap(byte data[], int offset) {
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data, offset, data.length-offset));
} catch (IOException e) {
LOG.log(POILogger.WARN, "Can't determine image dimensions", e);
}
// set dummy size, in case of dummy dimension can't be set
size = (img == null)
? new Dimension(200,200)
: new Dimension(
(int)Units.pixelToPoints(img.getWidth()),
(int)Units.pixelToPoints(img.getHeight())
);
}
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");
}
}
/**
* constructor that adds additional subdirectories to an existing
* path
*
* @param path the existing path
* @param components the additional subdirectory names to be added
*
* @exception IllegalArgumentException if any of the Strings in
* components is null or zero
* length
*/
public POIFSDocumentPath(final POIFSDocumentPath path,
final String [] components)
throws IllegalArgumentException
{
if (components == null)
{
this.components = new String[ path.components.length ];
}
else
{
this.components =
new String[ path.components.length + components.length ];
}
for (int j = 0; j < path.components.length; j++)
{
this.components[ j ] = path.components[ j ];
}
if (components != null)
{
for (int j = 0; j < components.length; j++)
{
if (components[ j ] == null)
{
throw new IllegalArgumentException(
"components cannot contain null");
}
if (components[ j ].length() == 0)
{
log.log(POILogger.WARN, "Directory under " + path + " has an empty name, " +
"not all OLE2 readers will handle this file correctly!");
}
this.components[ j + path.components.length ] =
components[ j ];
}
}
}
/**
* @param stream the stream to be closed
* @param success <code>false</code> if an exception is currently being thrown in the calling method
*/
private void closeInputStream(InputStream stream, boolean success) {
try {
stream.close();
} catch (IOException e) {
if(success) {
throw new RuntimeException(e);
}
// else not success? Try block did not complete normally
// just print stack trace and leave original ex to be thrown
LOG.log(POILogger.ERROR, "can't close input stream", e);
}
}