Search in sources :

Example 86 with FrameworkException

use of org.structr.common.error.FrameworkException in project structr by structr.

the class SyncCommand method exportToStream.

/**
 * Exports the given part of the structr database to the given output stream.
 *
 * @param outputStream
 * @param nodes
 * @param relationships
 * @param filePaths
 * @param includeFiles
 * @throws FrameworkException
 */
public static void exportToStream(final OutputStream outputStream, final Iterable<? extends NodeInterface> nodes, final Iterable<? extends RelationshipInterface> relationships, final Iterable<String> filePaths, final boolean includeFiles) throws FrameworkException {
    try (final ZipOutputStream zos = new ZipOutputStream(outputStream)) {
        final Set<String> filesToInclude = new LinkedHashSet<>();
        if (filePaths != null) {
            for (String file : filePaths) {
                filesToInclude.add(file);
            }
        }
        // set compression
        zos.setLevel(6);
        if (includeFiles) {
            logger.info("Exporting files..");
            // export files first
            exportDirectory(zos, new File("files"), "", filesToInclude.isEmpty() ? null : filesToInclude);
        }
        // export database
        exportDatabase(zos, new BufferedOutputStream(zos), nodes, relationships);
        // finish ZIP file
        zos.finish();
        // close stream
        zos.flush();
        zos.close();
    } catch (Throwable t) {
        logger.warn("", t);
        throw new FrameworkException(500, t.getMessage());
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) FrameworkException(org.structr.common.error.FrameworkException) ZipOutputStream(java.util.zip.ZipOutputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 87 with FrameworkException

use of org.structr.common.error.FrameworkException in project structr by structr.

the class SyncCommand method execute.

@Override
public void execute(final Map<String, Object> attributes) throws FrameworkException {
    DatabaseService graphDb = Services.getInstance().getService(NodeService.class).getGraphDb();
    String mode = (String) attributes.get("mode");
    String fileName = (String) attributes.get("file");
    String validate = (String) attributes.get("validate");
    String query = (String) attributes.get("query");
    Long batchSize = (Long) attributes.get("batchSize");
    boolean doValidation = true;
    // should we validate imported nodes?
    if (validate != null) {
        try {
            doValidation = Boolean.valueOf(validate);
        } catch (Throwable t) {
            logger.warn("Unable to parse value for validation flag: {}", t.getMessage());
        }
    }
    if (fileName == null) {
        throw new FrameworkException(400, "Please specify sync file.");
    }
    if ("export".equals(mode)) {
        exportToFile(graphDb, fileName, query, true);
    } else if ("exportDb".equals(mode)) {
        exportToFile(graphDb, fileName, query, false);
    } else if ("import".equals(mode)) {
        importFromFile(graphDb, securityContext, fileName, doValidation, batchSize);
    } else {
        throw new FrameworkException(400, "Please specify sync mode (import|export).");
    }
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) DatabaseService(org.structr.api.DatabaseService)

Example 88 with FrameworkException

use of org.structr.common.error.FrameworkException in project structr by structr.

the class TransactionCommand method commitTx.

public void commitTx(final boolean doValidation) throws FrameworkException {
    final TransactionReference tx = transactions.get();
    if (tx != null && tx.isToplevel()) {
        final ModificationQueue modificationQueue = queues.get();
        final ErrorBuffer errorBuffer = buffers.get();
        // 0.5: let transaction listeners examine (and prevent?) commit
        for (final StructrTransactionListener listener : listeners) {
            listener.beforeCommit(securityContext, modificationQueue.getModificationEvents(), tx.getSource());
        }
        // 1. do inner callbacks (may cause transaction to fail)
        if (!modificationQueue.doInnerCallbacks(securityContext, errorBuffer)) {
            tx.failure();
            throw new FrameworkException(422, "Unable to commit transaction, validation failed", errorBuffer);
        }
        // 2. fetch all types of entities modified in this tx
        Set<String> synchronizationKeys = modificationQueue.getSynchronizationKeys();
        // 3. acquire semaphores for each modified type
        try {
            semaphore.acquire(synchronizationKeys);
        } catch (InterruptedException iex) {
            return;
        }
        // do validation under the protection of the semaphores for each type
        if (doValidation && !modificationQueue.doValidation(securityContext, errorBuffer, doValidation)) {
            tx.failure();
            // create error
            throw new FrameworkException(422, "Unable to commit transaction, validation failed", errorBuffer);
        }
        // finally: execute validatable post-transaction action
        if (!modificationQueue.doPostProcessing(securityContext, errorBuffer)) {
            tx.failure();
            throw new FrameworkException(422, "Unable to commit transaction, transaction post processing failed", errorBuffer);
        }
        try {
            tx.success();
        } catch (Throwable t) {
            logger.error("Unable to commit transaction", t);
        }
    }
}
Also used : ErrorBuffer(org.structr.common.error.ErrorBuffer) FrameworkException(org.structr.common.error.FrameworkException) StructrTransactionListener(org.structr.core.StructrTransactionListener)

Example 89 with FrameworkException

use of org.structr.common.error.FrameworkException in project structr by structr.

the class Factory method page.

protected Result page(final QueryResult<S> input, final int offset, final int pageSize) throws FrameworkException {
    final SecurityContext securityContext = factoryProfile.getSecurityContext();
    final boolean dontCheckCount = securityContext.ignoreResultCount();
    final List<T> nodes = new ArrayList<>();
    int overallCount = 0;
    int position = 0;
    int count = 0;
    try (final QueryResult<S> tmp = input) {
        for (final S item : tmp) {
            final T n = instantiate(item);
            if (n != null) {
                overallCount++;
                position++;
                if (disablePaging || (position > offset && position <= offset + pageSize)) {
                    nodes.add(n);
                    // stop if we got enough nodes
                    if (++count == pageSize && dontCheckCount && !disablePaging) {
                        break;
                    }
                }
            }
        }
    } catch (NetworkException nex) {
        throw new FrameworkException(503, nex.getMessage());
    }
    // The overall count may be inaccurate
    return new Result(nodes, overallCount, true, false);
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) SecurityContext(org.structr.common.SecurityContext) ArrayList(java.util.ArrayList) NetworkException(org.structr.api.NetworkException) QueryResult(org.structr.api.QueryResult) Result(org.structr.core.Result)

Example 90 with FrameworkException

use of org.structr.common.error.FrameworkException in project structr by structr.

the class BulkCopyRelationshipPropertyCommand method execute.

@Override
public void execute(final Map<String, Object> map) throws FrameworkException {
    final DatabaseService graphDb = (DatabaseService) arguments.get("graphDb");
    final RelationshipFactory relFactory = new RelationshipFactory(securityContext);
    final String sourceKey = (String) map.get("sourceKey");
    final String destKey = (String) map.get("destKey");
    if (sourceKey == null || destKey == null) {
        throw new IllegalArgumentException("This command requires one argument of type Map. Map must contain values for 'sourceKey' and 'destKey'.");
    }
    if (graphDb != null) {
        final Iterator<AbstractRelationship> relIterator = Iterables.map(relFactory, graphDb.getAllRelationships()).iterator();
        final long count = bulkGraphOperation(securityContext, relIterator, 1000, "CopyRelationshipProperties", new BulkGraphOperation<AbstractRelationship>() {

            @Override
            public void handleGraphObject(SecurityContext securityContext, AbstractRelationship rel) {
                // Treat only "our" rels
                if (rel.getProperty(GraphObject.id) != null) {
                    Class type = rel.getClass();
                    PropertyKey destPropertyKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, destKey);
                    PropertyKey sourcePropertyKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sourceKey);
                    try {
                        // copy properties
                        rel.setProperty(destPropertyKey, rel.getProperty(sourcePropertyKey));
                    } catch (FrameworkException fex) {
                        logger.warn("Unable to copy relationship property {} of relationship {} to {}: {}", new Object[] { sourcePropertyKey, rel.getUuid(), destPropertyKey, fex.getMessage() });
                    }
                }
            }

            @Override
            public void handleThrowable(SecurityContext securityContext, Throwable t, AbstractRelationship rel) {
                logger.warn("Unable to copy relationship properties of relationship {}: {}", new Object[] { rel.getUuid(), t.getMessage() });
            }

            @Override
            public void handleTransactionFailure(SecurityContext securityContext, Throwable t) {
                logger.warn("Unable to copy relationship properties: {}", t.getMessage());
            }
        });
        logger.info("Finished setting properties on {} nodes", count);
    }
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) AbstractRelationship(org.structr.core.entity.AbstractRelationship) DatabaseService(org.structr.api.DatabaseService) SecurityContext(org.structr.common.SecurityContext) GraphObject(org.structr.core.GraphObject) PropertyKey(org.structr.core.property.PropertyKey)

Aggregations

FrameworkException (org.structr.common.error.FrameworkException)892 Tx (org.structr.core.graph.Tx)673 Test (org.junit.Test)450 App (org.structr.core.app.App)175 StructrApp (org.structr.core.app.StructrApp)174 StructrUiTest (org.structr.web.StructrUiTest)134 NodeInterface (org.structr.core.graph.NodeInterface)121 StructrTest (org.structr.common.StructrTest)118 PropertyKey (org.structr.core.property.PropertyKey)109 PropertyMap (org.structr.core.property.PropertyMap)105 IOException (java.io.IOException)96 GraphObject (org.structr.core.GraphObject)93 TestOne (org.structr.core.entity.TestOne)92 File (org.structr.web.entity.File)85 SecurityContext (org.structr.common.SecurityContext)78 Principal (org.structr.core.entity.Principal)69 Page (org.structr.web.entity.dom.Page)69 LinkedList (java.util.LinkedList)62 Folder (org.structr.web.entity.Folder)60 NodeAttribute (org.structr.core.graph.NodeAttribute)56