Search in sources :

Example 1 with MustBeLocked

use of com.helger.commons.annotation.MustBeLocked in project ph-commons by phax.

the class MimeTypeDeterminator method _registerDefaultMimeTypeContents.

@MustBeLocked(ELockType.WRITE)
private void _registerDefaultMimeTypeContents() {
    m_aMimeTypeContents.add(new MimeTypeContent(MIME_ID_GIF87A, false, CMimeType.IMAGE_GIF));
    m_aMimeTypeContents.add(new MimeTypeContent(MIME_ID_GIF89A, false, CMimeType.IMAGE_GIF));
    m_aMimeTypeContents.add(new MimeTypeContent(MIME_ID_JPG, false, CMimeType.IMAGE_JPG));
    m_aMimeTypeContents.add(new MimeTypeContent(MIME_ID_PNG, false, CMimeType.IMAGE_PNG));
    m_aMimeTypeContents.add(new MimeTypeContent(MIME_ID_TIFF_MOTOROLLA, false, CMimeType.IMAGE_TIFF));
    m_aMimeTypeContents.add(new MimeTypeContent(MIME_ID_TIFF_INTEL, false, CMimeType.IMAGE_TIFF));
    m_aMimeTypeContents.add(new MimeTypeContent(MIME_ID_PSD, false, CMimeType.IMAGE_PSD));
    m_aMimeTypeContents.add(new MimeTypeContent(MIME_ID_PDF, false, CMimeType.APPLICATION_PDF));
    m_aMimeTypeContents.add(new MimeTypeContent(MIME_ID_XLS, false, CMimeType.APPLICATION_MS_EXCEL));
    // Add all XML mime types: as the combination of all BOMs and all character
    // encodings as determined by
    // http://www.w3.org/TR/REC-xml/#sec-guessing
    final ICommonsList<byte[]> aXMLStuff = new CommonsArrayList<>();
    // UCS4
    aXMLStuff.add(new byte[] { 0x3c, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00 });
    aXMLStuff.add(new byte[] { 0x00, 0x3c, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00 });
    aXMLStuff.add(new byte[] { 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x3f, 0x00 });
    aXMLStuff.add(new byte[] { 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x3f });
    // UTF-16
    aXMLStuff.add(new byte[] { 0x00, 0x3c, 0x00, 0x3f });
    aXMLStuff.add(new byte[] { 0x3c, 0x00, 0x3f, 0x00 });
    // ISO-8859-1/UTF-8/ASCII etc.
    aXMLStuff.add(new byte[] { 0x3c, 0x3f, 0x78, 0x6d });
    // EBCDIC
    aXMLStuff.add(new byte[] { 0x4c, 0x6f, (byte) 0xa7, (byte) 0x94 });
    // Register all types without the BOM
    aXMLStuff.forEach(aXML -> registerMimeTypeContent(new MimeTypeContent(aXML, false, CMimeType.TEXT_XML)));
    // Register all type with the BOM
    for (final EUnicodeBOM eBOM : EUnicodeBOM.values()) for (final byte[] aXML : aXMLStuff) {
        final byte[] aData = ArrayHelper.getConcatenated(eBOM.getAllBytes(), aXML);
        registerMimeTypeContent(new MimeTypeContent(aData, false, CMimeType.TEXT_XML));
    }
}
Also used : EUnicodeBOM(com.helger.commons.charset.EUnicodeBOM) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) MustBeLocked(com.helger.commons.annotation.MustBeLocked)

Example 2 with MustBeLocked

use of com.helger.commons.annotation.MustBeLocked in project ph-commons by phax.

the class AbstractSimpleDAO method modifyWriteData.

/**
 * Modify the created document by e.g. adding some comment or digital
 * signature or whatsoever.
 *
 * @param aDoc
 *        The created non-<code>null</code> document.
 */
@OverrideOnDemand
@MustBeLocked(ELockType.WRITE)
protected void modifyWriteData(@Nonnull final IMicroDocument aDoc) {
    final IMicroComment aComment = new MicroComment("This file was generated automatically - do NOT modify!\n" + "Written at " + PDTToString.getAsString(ZonedDateTime.now(Clock.systemUTC()), Locale.US));
    final IMicroElement eRoot = aDoc.getDocumentElement();
    // Add a small comment
    if (eRoot != null)
        aDoc.insertBefore(aComment, eRoot);
    else
        aDoc.appendChild(aComment);
}
Also used : MicroComment(com.helger.xml.microdom.MicroComment) IMicroComment(com.helger.xml.microdom.IMicroComment) IMicroElement(com.helger.xml.microdom.IMicroElement) IMicroComment(com.helger.xml.microdom.IMicroComment) MustBeLocked(com.helger.commons.annotation.MustBeLocked) OverrideOnDemand(com.helger.commons.annotation.OverrideOnDemand)

Example 3 with MustBeLocked

use of com.helger.commons.annotation.MustBeLocked in project ph-commons by phax.

the class AbstractSimpleDAO method initialRead.

/**
 * Call this method inside the constructor to read the file contents directly.
 * This method is write locked!
 *
 * @throws DAOException
 *         in case initialization or reading failed!
 */
@MustBeLocked(ELockType.WRITE)
protected final void initialRead() throws DAOException {
    File aFile = null;
    final String sFilename = m_aFilenameProvider.get();
    if (sFilename == null) {
        // required for testing
        if (!isSilentMode())
            if (LOGGER.isInfoEnabled())
                LOGGER.info("This DAO of class " + getClass().getName() + " will not be able to read from a file");
    // do not return - run initialization anyway
    } else {
        // Check consistency
        aFile = getSafeFile(sFilename, EMode.READ);
    }
    final File aFinalFile = aFile;
    m_aRWLock.writeLockedThrowing(() -> {
        final boolean bIsInitialization = aFinalFile == null || !aFinalFile.exists();
        try {
            ESuccess eWriteSuccess = ESuccess.SUCCESS;
            if (bIsInitialization) {
                // initial setup for non-existing file
                if (!isSilentMode())
                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("Trying to initialize DAO XML file '" + aFinalFile + "'");
                beginWithoutAutoSave();
                try {
                    m_aStatsCounterInitTotal.increment();
                    final StopWatch aSW = StopWatch.createdStarted();
                    if (onInit().isChanged())
                        if (aFinalFile != null)
                            eWriteSuccess = _writeToFile();
                    m_aStatsCounterInitTimer.addTime(aSW.stopAndGetMillis());
                    m_aStatsCounterInitSuccess.increment();
                    m_nInitCount++;
                    m_aLastInitDT = PDTFactory.getCurrentLocalDateTime();
                } finally {
                    endWithoutAutoSave();
                    // reset any pending changes, because the initialization should
                    // be read-only. If the implementing class changed something,
                    // the return value of onInit() is what counts
                    internalSetPendingChanges(false);
                }
            } else {
                // Read existing file
                if (!isSilentMode())
                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("Trying to read DAO XML file '" + aFinalFile + "'");
                m_aStatsCounterReadTotal.increment();
                final IMicroDocument aDoc = MicroReader.readMicroXML(aFinalFile);
                if (aDoc == null) {
                    if (LOGGER.isErrorEnabled())
                        LOGGER.error("Failed to read XML document from file '" + aFinalFile + "'");
                } else {
                    // Valid XML - start interpreting
                    beginWithoutAutoSave();
                    try {
                        final StopWatch aSW = StopWatch.createdStarted();
                        if (onRead(aDoc).isChanged())
                            eWriteSuccess = _writeToFile();
                        m_aStatsCounterReadTimer.addTime(aSW.stopAndGetMillis());
                        m_aStatsCounterReadSuccess.increment();
                        m_nReadCount++;
                        m_aLastReadDT = PDTFactory.getCurrentLocalDateTime();
                    } finally {
                        endWithoutAutoSave();
                        // reset any pending changes, because the initialization should
                        // be read-only. If the implementing class changed something,
                        // the return value of onRead() is what counts
                        internalSetPendingChanges(false);
                    }
                }
            }
            // Check if writing was successful on any of the 2 branches
            if (eWriteSuccess.isSuccess())
                internalSetPendingChanges(false);
            else {
                if (LOGGER.isErrorEnabled())
                    LOGGER.error("File '" + aFinalFile + "' has pending changes after initialRead!");
            }
        } catch (final Exception ex) {
            triggerExceptionHandlersRead(ex, bIsInitialization, aFinalFile);
            throw new DAOException("Error " + (bIsInitialization ? "initializing" : "reading") + " the file '" + aFinalFile + "'", ex);
        }
    });
}
Also used : ESuccess(com.helger.commons.state.ESuccess) DAOException(com.helger.dao.DAOException) PDTToString(com.helger.commons.datetime.PDTToString) IMicroDocument(com.helger.xml.microdom.IMicroDocument) File(java.io.File) DAOException(com.helger.dao.DAOException) StopWatch(com.helger.commons.timing.StopWatch) MustBeLocked(com.helger.commons.annotation.MustBeLocked)

Example 4 with MustBeLocked

use of com.helger.commons.annotation.MustBeLocked in project ph-commons by phax.

the class AbstractSimpleDAO method _writeToFile.

/**
 * The main method for writing the new data to a file. This method may only be
 * called within a write lock!
 *
 * @return {@link ESuccess} and never <code>null</code>.
 */
@Nonnull
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
@MustBeLocked(ELockType.WRITE)
private ESuccess _writeToFile() {
    // Build the filename to write to
    final String sFilename = m_aFilenameProvider.get();
    if (sFilename == null) {
        // We're not operating on a file! Required for testing
        if (!isSilentMode())
            if (LOGGER.isInfoEnabled())
                LOGGER.info("The DAO of class " + getClass().getName() + " cannot write to a file");
        return ESuccess.FAILURE;
    }
    // Check for a filename change before writing
    if (!sFilename.equals(m_sPreviousFilename)) {
        onFilenameChange(m_sPreviousFilename, sFilename);
        m_sPreviousFilename = sFilename;
    }
    if (!isSilentMode())
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Trying to write DAO file '" + sFilename + "'");
    File aFile = null;
    IMicroDocument aDoc = null;
    try {
        // Get the file handle
        aFile = getSafeFile(sFilename, EMode.WRITE);
        m_aStatsCounterWriteTotal.increment();
        final StopWatch aSW = StopWatch.createdStarted();
        // Create XML document to write
        aDoc = createWriteData();
        if (aDoc == null)
            throw new DAOException("Failed to create data to write to file");
        // Generic modification
        modifyWriteData(aDoc);
        // Perform optional stuff like backup etc. Must be done BEFORE the output
        // stream is opened!
        beforeWriteToFile(sFilename, aFile);
        // Get the output stream
        final OutputStream aOS = FileHelper.getOutputStream(aFile);
        if (aOS == null) {
            // Logger warning already emitted
            throw new DAOException("Failed to open output stream");
        }
        // Write to file (closes the OS)
        final IXMLWriterSettings aXWS = getXMLWriterSettings();
        if (MicroWriter.writeToStream(aDoc, aOS, aXWS).isFailure())
            throw new DAOException("Failed to write DAO XML data to file");
        m_aStatsCounterWriteTimer.addTime(aSW.stopAndGetMillis());
        m_aStatsCounterWriteSuccess.increment();
        m_nWriteCount++;
        m_aLastWriteDT = PDTFactory.getCurrentLocalDateTime();
        return ESuccess.SUCCESS;
    } catch (final Exception ex) {
        final String sErrorFilename = aFile != null ? aFile.getAbsolutePath() : sFilename;
        if (LOGGER.isErrorEnabled())
            LOGGER.error("The DAO of class " + getClass().getName() + " failed to write the DAO data to '" + sErrorFilename + "'", ex);
        triggerExceptionHandlersWrite(ex, sErrorFilename, aDoc);
        m_aStatsCounterWriteExceptions.increment();
        return ESuccess.FAILURE;
    }
}
Also used : DAOException(com.helger.dao.DAOException) IXMLWriterSettings(com.helger.xml.serialize.write.IXMLWriterSettings) OutputStream(java.io.OutputStream) PDTToString(com.helger.commons.datetime.PDTToString) IMicroDocument(com.helger.xml.microdom.IMicroDocument) File(java.io.File) DAOException(com.helger.dao.DAOException) StopWatch(com.helger.commons.timing.StopWatch) MustBeLocked(com.helger.commons.annotation.MustBeLocked) Nonnull(javax.annotation.Nonnull) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 5 with MustBeLocked

use of com.helger.commons.annotation.MustBeLocked in project ph-commons by phax.

the class AbstractMapBasedWALDAO method createWriteData.

@Override
@Nonnull
@MustBeLocked(ELockType.READ)
protected IMicroDocument createWriteData() {
    final IMicroDocument aDoc = new MicroDocument();
    final IMicroElement eRoot = aDoc.appendElement(ELEMENT_ROOT);
    for (final IMPLTYPE aItem : internalGetAllSortedByKey()) eRoot.appendChild(MicroTypeConverter.convertToMicroElement(aItem, ELEMENT_ITEM));
    return aDoc;
}
Also used : IMicroDocument(com.helger.xml.microdom.IMicroDocument) MicroDocument(com.helger.xml.microdom.MicroDocument) IMicroElement(com.helger.xml.microdom.IMicroElement) IMicroDocument(com.helger.xml.microdom.IMicroDocument) MustBeLocked(com.helger.commons.annotation.MustBeLocked) Nonnull(javax.annotation.Nonnull)

Aggregations

MustBeLocked (com.helger.commons.annotation.MustBeLocked)10 PDTToString (com.helger.commons.datetime.PDTToString)5 IMicroDocument (com.helger.xml.microdom.IMicroDocument)5 DAOException (com.helger.dao.DAOException)4 Nonnull (javax.annotation.Nonnull)4 StopWatch (com.helger.commons.timing.StopWatch)3 IMicroElement (com.helger.xml.microdom.IMicroElement)3 File (java.io.File)3 OverrideOnDemand (com.helger.commons.annotation.OverrideOnDemand)2 FileIOError (com.helger.commons.io.file.FileIOError)2 IMicroComment (com.helger.xml.microdom.IMicroComment)2 MicroComment (com.helger.xml.microdom.MicroComment)2 IXMLWriterSettings (com.helger.xml.serialize.write.IXMLWriterSettings)2 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)2 DataOutputStream (java.io.DataOutputStream)2 OutputStream (java.io.OutputStream)2 EUnicodeBOM (com.helger.commons.charset.EUnicodeBOM)1 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)1 FileSystemResource (com.helger.commons.io.resource.FileSystemResource)1 ESuccess (com.helger.commons.state.ESuccess)1