Search in sources :

Example 61 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class FormResourceV1 method get.

/**
 * Return the current state of a form instance.
 */
@GET
@ApiOperation("Get the current state of a form")
@Path("/{processInstanceId}/form/{formName}")
@Produces(MediaType.APPLICATION_JSON)
public FormInstanceEntry get(@ApiParam @PathParam("processInstanceId") UUID processInstanceId, @ApiParam @PathParam("formName") String formName) {
    PartialProcessKey processKey = PartialProcessKey.from(processInstanceId);
    Form form = formService.get(processKey, formName);
    if (form == null) {
        throw new ConcordApplicationException("Form " + formName + " not found. Process ID: " + processKey, Status.NOT_FOUND);
    }
    Map<String, Object> data = FormUtils.values(form);
    boolean yield = MapUtils.getBoolean(form.getOptions(), "yield", false);
    Map<String, Object> allowedValues = form.getAllowedValues();
    if (allowedValues == null) {
        allowedValues = Collections.emptyMap();
    }
    List<FormInstanceEntry.Field> fields = new ArrayList<>();
    FormDefinition fd = form.getFormDefinition();
    for (FormField f : fd.getFields()) {
        String fieldName = f.getName();
        FormInstanceEntry.Cardinality c = map(f.getCardinality());
        String type = f.getType();
        Object value = data.get(fieldName);
        Object allowedValue = allowedValues.get(fieldName);
        fields.add(new FormInstanceEntry.Field(fieldName, f.getLabel(), type, c, value, allowedValue, f.getOptions()));
    }
    String pbk = form.getProcessBusinessKey();
    String name = fd.getName();
    String resourcePath = FORMS_RESOURCES_PATH + "/" + name;
    boolean isCustomForm = formService.exists(processKey, resourcePath);
    return new FormInstanceEntry(pbk, name, fields, isCustomForm, yield);
}
Also used : PartialProcessKey(com.walmartlabs.concord.server.sdk.PartialProcessKey) Form(io.takari.bpm.form.Form) FormField(io.takari.bpm.model.form.FormField) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) FormDefinition(io.takari.bpm.model.form.FormDefinition) FormField(io.takari.bpm.model.form.FormField) ApiOperation(io.swagger.annotations.ApiOperation)

Example 62 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class FormUtils method convert.

private static Object convert(ConcordFormValidatorLocale locale, String formName, FormField f, Integer idx, Object v) throws ValidationException {
    if (v instanceof String) {
        String s = (String) v;
        switch(f.getType()) {
            case DefaultFormFields.StringField.TYPE:
                {
                    if (s.isEmpty()) {
                        return null;
                    }
                    break;
                }
            case DefaultFormFields.IntegerField.TYPE:
                {
                    if (s.isEmpty()) {
                        return null;
                    }
                    try {
                        return Long.parseLong(s);
                    } catch (NumberFormatException e) {
                        throw new ValidationException(f, s, locale.expectedInteger(formName, f, idx, s));
                    }
                }
            case DefaultFormFields.DecimalField.TYPE:
                {
                    if (s.isEmpty()) {
                        return null;
                    }
                    try {
                        return Double.parseDouble(s);
                    } catch (NumberFormatException e) {
                        throw new ValidationException(f, s, locale.expectedDecimal(formName, f, idx, s));
                    }
                }
            case DefaultFormFields.BooleanField.TYPE:
                {
                    if (s.isEmpty()) {
                        // default HTML checkbox will be submitted as an empty value if checked
                        return true;
                    }
                    return Boolean.parseBoolean(s);
                }
            case ConcordFormFields.FileField.TYPE:
                {
                    try {
                        Path tmp = IOUtils.createTempFile(f.getName(), ".tmp");
                        Files.write(tmp, s.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
                        return tmp.toString();
                    } catch (IOException e) {
                        throw new ConcordApplicationException("Error reading file for form field '" + f.getName() + "'", e);
                    }
                }
            case ConcordFormFields.DateField.TYPE:
            case ConcordFormFields.DateTimeField.TYPE:
                {
                    if (s.isEmpty()) {
                        return null;
                    }
                    // so we assume all Date values are in the default system TZ (which is typically UTC)
                    return ZonedDateTime.parse(s).withZoneSameInstant(DEFAULT_TIME_ZONE).format(DATE_TIME_FORMATTER);
                }
        }
    } else if (v instanceof List) {
        List<?> l = (List<?>) v;
        if (l.isEmpty()) {
            return null;
        }
        List<Object> ll = new ArrayList<>(l.size());
        int i = 0;
        for (Object o : l) {
            ll.add(convert(locale, formName, f, i, o));
            i++;
        }
        return ll;
    } else if (v instanceof InputStream) {
        if (f.getType().equals(ConcordFormFields.FileField.TYPE)) {
            try (InputStream is = (InputStream) v) {
                Path tmp = IOUtils.createTempFile(f.getName(), ".tmp");
                Files.copy(is, tmp, REPLACE_EXISTING);
                return tmp.toString();
            } catch (IOException e) {
                throw new ConcordApplicationException("Error reading file for form field '" + f.getName() + "'", e);
            }
        }
    } else if (v == null) {
        if (f.getType().equals(DefaultFormFields.BooleanField.TYPE)) {
            return false;
        }
    }
    return v;
}
Also used : Path(java.nio.file.Path) InputStream(java.io.InputStream) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) IOException(java.io.IOException)

Example 63 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class ProcessDefinitionProcessor method process.

@Override
public Payload process(Chain chain, Payload payload) {
    ProcessKey processKey = payload.getProcessKey();
    Path workDir = payload.getHeader(Payload.WORKSPACE_DIR);
    if (workDir == null) {
        return chain.process(payload);
    }
    UUID projectId = payload.getHeader(Payload.PROJECT_ID);
    try {
        String runtime = getRuntimeType(payload);
        ProjectLoader.Result result = projectLoader.loadProject(workDir, runtime, importsNormalizer.forProject(projectId), new ProcessImportsListener(processKey));
        List<Snapshot> snapshots = result.snapshots();
        payload = PayloadUtils.addSnapshots(payload, snapshots);
        ProcessDefinition pd = result.projectDefinition();
        int depsCount = pd.configuration().dependencies().size();
        if (depsCount > MAX_DEPENDENCIES_COUNT) {
            String msg = String.format("Too many dependencies. Current: %d, maximum allowed: %d", depsCount, MAX_DEPENDENCIES_COUNT);
            throw new ConcordApplicationException(msg, Response.Status.BAD_REQUEST);
        }
        payload = payload.putHeader(Payload.PROJECT_DEFINITION, pd).putHeader(Payload.RUNTIME, pd.runtime()).putHeader(Payload.IMPORTS, pd.imports()).putHeader(Payload.DEPENDENCIES, pd.configuration().dependencies());
        // save the runtime type in the process configuration
        Map<String, Object> cfg = payload.getHeader(Payload.CONFIGURATION, Collections.emptyMap());
        // make mutable
        cfg = new HashMap<>(cfg);
        cfg.put(Constants.Request.RUNTIME_KEY, runtime);
        payload = payload.putHeader(Payload.CONFIGURATION, cfg);
    } catch (ImportProcessingException e) {
        throw new ProcessException(processKey, "Error while processing import " + e.getImport() + ". Error: " + e.getMessage(), e);
    } catch (Exception e) {
        log.warn("process -> ({}) project loading error: {}", workDir, e.getMessage());
        throw new ProcessException(processKey, "Error while loading the project, check the syntax. " + e.getMessage(), e);
    }
    return chain.process(payload);
}
Also used : Path(java.nio.file.Path) ImportProcessingException(com.walmartlabs.concord.imports.ImportProcessingException) ProcessDefinition(com.walmartlabs.concord.process.loader.model.ProcessDefinition) ProcessKey(com.walmartlabs.concord.server.sdk.ProcessKey) ProjectLoader(com.walmartlabs.concord.process.loader.ProjectLoader) ProcessException(com.walmartlabs.concord.server.process.ProcessException) IOException(java.io.IOException) ImportProcessingException(com.walmartlabs.concord.imports.ImportProcessingException) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) Snapshot(com.walmartlabs.concord.repository.Snapshot) ProcessException(com.walmartlabs.concord.server.process.ProcessException) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException)

Example 64 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class ProcessLocksResource method assertProcess.

private ProcessEntry assertProcess(UUID instanceId) {
    PartialProcessKey processKey = PartialProcessKey.from(instanceId);
    ProcessEntry p = processQueueManager.get(processKey);
    if (p == null) {
        throw new ConcordApplicationException("Process not found: " + instanceId, Response.Status.NOT_FOUND);
    }
    if (p.orgId() == null) {
        throw new ConcordApplicationException("Organization is required", Response.Status.BAD_REQUEST);
    }
    if (p.projectId() == null) {
        throw new ConcordApplicationException("Project is required", Response.Status.BAD_REQUEST);
    }
    return p;
}
Also used : PartialProcessKey(com.walmartlabs.concord.server.sdk.PartialProcessKey) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) ProcessEntry(com.walmartlabs.concord.server.process.ProcessEntry)

Example 65 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class SecretManager method update.

public void update(UUID orgId, String secretName, SecretUpdateParams params) {
    SecretEntry e = assertAccess(orgId, null, secretName, ResourceAccessLevel.WRITER, false);
    UUID newOrgId = validateOrgId(params.newOrgId(), params.newOrgName(), e);
    UUID newProjectId = validateProjectId(params.newProjectId(), params.newProjectName(), params.removeProjectLink(), newOrgId, e);
    UserEntry newOwner = validateOwner(params.newOwnerId(), e);
    String currentPassword = params.currentPassword();
    String newPassword = params.newPassword();
    if (e.getEncryptedBy() == SecretEncryptedByType.SERVER_KEY && (currentPassword != null || newPassword != null)) {
        throw new ConcordApplicationException("The secret is encrypted with the server's key, the '" + Constants.Multipart.STORE_PASSWORD + "' cannot be changed", Status.BAD_REQUEST);
    }
    Map<String, Object> updated = new HashMap<>();
    byte[] newData = null;
    SecretType newType = null;
    if (params.newSecret() != null) {
        // updating the data and/or the store password
        if (e.getEncryptedBy() == SecretEncryptedByType.PASSWORD && currentPassword == null) {
            throw new ConcordApplicationException("Updating the secret's data requires the original '" + Constants.Multipart.STORE_PASSWORD + "'", Status.BAD_REQUEST);
        }
        // validate the current password
        decryptData(e.getId(), e.getStoreType(), currentPassword);
        newData = serialize(params.newSecret());
        newType = secretType(params.newSecret());
        updated.put("data", true);
    } else if (newPassword != null) {
        // keeping the old data, just changing the store password
        newData = decryptData(e.getId(), e.getStoreType(), currentPassword);
    }
    String pwd = currentPassword;
    if (newPassword != null && !newPassword.equals(currentPassword)) {
        pwd = newPassword;
        updated.put("password", true);
    }
    byte[] newEncryptedData;
    if (newData != null) {
        // encrypt the supplied data
        byte[] salt = secretCfg.getSecretStoreSalt();
        newEncryptedData = SecretUtils.encrypt(newData, getPwd(pwd), salt);
    } else {
        newEncryptedData = null;
    }
    policyManager.checkEntity(e.getOrgId(), newProjectId, EntityType.SECRET, EntityAction.UPDATE, newOwner, PolicyUtils.secretToMap(e.getOrgId(), e.getName(), e.getType(), e.getVisibility(), e.getStoreType()));
    String newName = validateName(params.newName(), newOrgId, e);
    SecretType finalNewType = newType;
    secretDao.tx(tx -> {
        if (newOrgId != null) {
            // update repository mapping to null when org is changing
            repositoryDao.clearSecretMappingBySecretId(tx, e.getId());
        }
        secretDao.update(tx, e.getId(), params.newName(), newOwner != null ? newOwner.getId() : null, finalNewType, newEncryptedData, params.newVisibility(), newProjectId, newOrgId);
    });
    Map<String, Object> changes = DiffUtils.compare(e, secretDao.get(e.getId()));
    changes.put("updated", updated);
    auditLog.add(AuditObject.SECRET, AuditAction.UPDATE).field("orgId", e.getOrgId()).field("secretId", e.getId()).field("name", e.getName()).field("changes", changes).log();
}
Also used : ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) UserEntry(com.walmartlabs.concord.server.user.UserEntry) AuditObject(com.walmartlabs.concord.server.audit.AuditObject)

Aggregations

ConcordApplicationException (com.walmartlabs.concord.server.sdk.ConcordApplicationException)70 ApiOperation (io.swagger.annotations.ApiOperation)28 UUID (java.util.UUID)22 WithTimer (com.walmartlabs.concord.server.sdk.metrics.WithTimer)21 PartialProcessKey (com.walmartlabs.concord.server.sdk.PartialProcessKey)18 IOException (java.io.IOException)14 ValidationErrorsException (org.sonatype.siesta.ValidationErrorsException)12 GenericOperationResult (com.walmartlabs.concord.server.GenericOperationResult)11 ProcessKey (com.walmartlabs.concord.server.sdk.ProcessKey)11 Validate (org.sonatype.siesta.Validate)11 Path (java.nio.file.Path)10 UserPrincipal (com.walmartlabs.concord.server.security.UserPrincipal)9 OrganizationEntry (com.walmartlabs.concord.server.org.OrganizationEntry)8 EntryPoint (com.walmartlabs.concord.server.process.PayloadManager.EntryPoint)6 ProcessStatus (com.walmartlabs.concord.server.sdk.ProcessStatus)6 UnauthorizedException (org.apache.shiro.authz.UnauthorizedException)6 UserEntry (com.walmartlabs.concord.server.user.UserEntry)5 InputStream (java.io.InputStream)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 Form (com.walmartlabs.concord.forms.Form)3