Search in sources :

Example 1 with ErrorBuffer

use of org.structr.common.error.ErrorBuffer 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 2 with ErrorBuffer

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

the class TransactionCommand method beginTx.

public TransactionCommand beginTx() throws FrameworkException {
    final DatabaseService graphDb = (DatabaseService) arguments.get("graphDb");
    TransactionReference tx = transactions.get();
    if (graphDb != null) {
        if (tx == null) {
            try {
                // start new transaction
                tx = new TransactionReference(graphDb.beginTx());
            } catch (NetworkException nex) {
                throw new DatabaseServiceNetworkException(503, nex.getMessage());
            }
            queues.set(new ModificationQueue());
            buffers.set(new ErrorBuffer());
            transactions.set(tx);
            currentCommand.set(this);
        }
        // increase depth
        tx.begin();
    } else {
        throw new DatabaseServiceNotAvailableException(503, "Database service is not available, ensure the database is running and that there is a working network connection to it");
    }
    return this;
}
Also used : ErrorBuffer(org.structr.common.error.ErrorBuffer) DatabaseServiceNotAvailableException(org.structr.common.error.DatabaseServiceNotAvailableException) DatabaseService(org.structr.api.DatabaseService) NetworkException(org.structr.api.NetworkException) DatabaseServiceNetworkException(org.structr.common.error.DatabaseServiceNetworkException) DatabaseServiceNetworkException(org.structr.common.error.DatabaseServiceNetworkException)

Example 3 with ErrorBuffer

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

the class Services method command.

/**
 * Creates and returns a command of the given <code>type</code>. If a command is
 * found, the corresponding service will be discovered and activated.
 *
 * @param <T>
 * @param securityContext
 * @param commandType the runtime type of the desired command
 * @return the command
 */
public <T extends Command> T command(final SecurityContext securityContext, final Class<T> commandType) {
    try {
        final T command = commandType.newInstance();
        final Class serviceClass = command.getServiceClass();
        // inject security context first
        command.setArgument("securityContext", securityContext);
        if ((serviceClass != null) && configuredServiceClasses.contains(serviceClass.getSimpleName())) {
            // search for already running service..
            Service service = serviceCache.get(serviceClass);
            if (service == null) {
                // start service
                startService(serviceClass);
                // reload service
                service = serviceCache.get(serviceClass);
                if (serviceClass.equals(NodeService.class)) {
                    logger.debug("(Re-)Started NodeService, (re-)compiling dynamic schema");
                    SchemaService.reloadSchema(new ErrorBuffer(), null);
                }
            }
            if (service != null) {
                logger.debug("Initializing command ", commandType.getName());
                service.injectArguments(command);
            }
        }
        command.initialized();
        return command;
    } catch (Throwable t) {
        logger.error("Exception while creating command {}", commandType.getName());
    }
    return null;
}
Also used : ErrorBuffer(org.structr.common.error.ErrorBuffer) DatabaseService(org.structr.api.DatabaseService) NodeService(org.structr.core.graph.NodeService) ExecutorService(java.util.concurrent.ExecutorService) Service(org.structr.api.service.Service) RunnableService(org.structr.api.service.RunnableService) SchemaService(org.structr.schema.SchemaService)

Example 4 with ErrorBuffer

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

the class SchemaHelper method getSourceGenerator.

// ----- private methods -----
private static PropertySourceGenerator getSourceGenerator(final ErrorBuffer errorBuffer, final String className, final PropertyDefinition propertyDefinition) throws FrameworkException {
    final String propertyName = propertyDefinition.getPropertyName();
    final Type propertyType = propertyDefinition.getPropertyType();
    final Class<? extends PropertySourceGenerator> parserClass = parserMap.get(propertyType);
    try {
        return parserClass.getConstructor(ErrorBuffer.class, String.class, PropertyDefinition.class).newInstance(errorBuffer, className, propertyDefinition);
    } catch (Throwable t) {
        logger.warn("", t);
    }
    errorBuffer.add(new InvalidPropertySchemaToken(SchemaProperty.class.getSimpleName(), propertyName, propertyName, "invalid_property_definition", "Unknow value type " + source + ", options are " + Arrays.asList(Type.values()) + "."));
    throw new FrameworkException(422, "Invalid property definition for property " + propertyDefinition.getPropertyName(), errorBuffer);
}
Also used : GraphQLScalarType(graphql.schema.GraphQLScalarType) GraphQLOutputType(graphql.schema.GraphQLOutputType) ErrorBuffer(org.structr.common.error.ErrorBuffer) FrameworkException(org.structr.common.error.FrameworkException) InvalidPropertySchemaToken(org.structr.common.error.InvalidPropertySchemaToken) StringBasedPropertyDefinition(org.structr.schema.parser.StringBasedPropertyDefinition) PropertyDefinition(org.structr.schema.parser.PropertyDefinition)

Example 5 with ErrorBuffer

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

the class LogResource method doPost.

@Override
public RestMethodResult doPost(Map<String, Object> propertySet) throws FrameworkException {
    final HttpServletRequest request = securityContext.getRequest();
    if (request != null) {
        // initialize?!
        if ("true".equals(request.getParameter("initialize"))) {
            final String filesPath = Settings.FilesPath.getValue();
            try (final Context context = new Context(1000)) {
                collectFilesAndStore(context, new File(filesPath + SUBJECTS).toPath(), 0);
            } catch (FrameworkException fex) {
                logger.warn("", fex);
            }
            return new RestMethodResult(200);
        }
        final String subjectId = (String) propertySet.get(subjectProperty.jsonName());
        final String objectId = (String) propertySet.get(objectProperty.jsonName());
        final String action = (String) propertySet.get(actionProperty.jsonName());
        final String message = (String) propertySet.get(messageProperty.jsonName());
        if (subjectId != null && objectId != null && action != null) {
            final App app = StructrApp.getInstance(securityContext);
            LogEvent event = null;
            try (final Tx tx = app.tx()) {
                final PropertyMap properties = new PropertyMap();
                properties.put(LogEvent.timestampProperty, new Date());
                properties.put(LogEvent.actionProperty, action);
                properties.put(LogEvent.subjectProperty, subjectId);
                properties.put(LogEvent.objectProperty, objectId);
                properties.put(LogEvent.messageProperty, message);
                properties.put(LogEvent.visibleToPublicUsers, true);
                properties.put(LogEvent.visibleToAuthenticatedUsers, true);
                event = app.create(LogEvent.class, properties);
                tx.success();
            }
            final RestMethodResult result = new RestMethodResult(201);
            result.addContent(event);
            return result;
        } else {
            final ErrorBuffer errorBuffer = new ErrorBuffer();
            if (StringUtils.isEmpty(subjectId)) {
                errorBuffer.add(new EmptyPropertyToken("LogFile", subjectProperty));
            }
            if (StringUtils.isEmpty(objectId)) {
                errorBuffer.add(new EmptyPropertyToken("LogFile", objectProperty));
            }
            if (StringUtils.isEmpty(action)) {
                errorBuffer.add(new EmptyPropertyToken("LogFile", actionProperty));
            }
            throw new FrameworkException(422, "Log entry must consist of at least subjectId, objectId and action", errorBuffer);
        }
    }
    // no request object, this is fatal
    throw new FrameworkException(500, "No request object present, aborting.");
}
Also used : SecurityContext(org.structr.common.SecurityContext) App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) EmptyPropertyToken(org.structr.common.error.EmptyPropertyToken) FrameworkException(org.structr.common.error.FrameworkException) Tx(org.structr.core.graph.Tx) LogEvent(org.structr.rest.logging.entity.LogEvent) Date(java.util.Date) HttpServletRequest(javax.servlet.http.HttpServletRequest) PropertyMap(org.structr.core.property.PropertyMap) ErrorBuffer(org.structr.common.error.ErrorBuffer) File(java.io.File) RestMethodResult(org.structr.rest.RestMethodResult)

Aggregations

ErrorBuffer (org.structr.common.error.ErrorBuffer)16 FrameworkException (org.structr.common.error.FrameworkException)13 App (org.structr.core.app.App)4 StructrApp (org.structr.core.app.StructrApp)4 EmptyPropertyToken (org.structr.common.error.EmptyPropertyToken)3 LinkedList (java.util.LinkedList)2 DatabaseService (org.structr.api.DatabaseService)2 AbstractRelationship (org.structr.core.entity.AbstractRelationship)2 PropertyMap (org.structr.core.property.PropertyMap)2 RestMethodResult (org.structr.rest.RestMethodResult)2 GraphQLOutputType (graphql.schema.GraphQLOutputType)1 GraphQLScalarType (graphql.schema.GraphQLScalarType)1 BufferedInputStream (java.io.BufferedInputStream)1 DataInputStream (java.io.DataInputStream)1 EOFException (java.io.EOFException)1 File (java.io.File)1 DecimalFormat (java.text.DecimalFormat)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1