Search in sources :

Example 6 with Context

use of io.javalin.http.Context in project jenkins-scm-koji-plugin by judovana.

the class RedeployApi method addEndpoints.

@Override
public void addEndpoints() {
    get(LATEST, context -> {
        String countValue = context.queryParam(LATEST_count);
        String commentsValue = context.queryParam(PROCESSED_cmments);
        String jobsNamesValue = context.queryParam(PROCESSED_job);
        List<String> jobs = new RedeployApiWorkerBase.RedeployApiStringListing(context).process(jdkProjectManager, jdkTestProjectManager, parser);
        Set<String> nvrs = new HashSet<>(jobs.size());
        for (String job : jobs) {
            File processed = new File(new File(settings.getJenkinsJobsRoot(), job), Constants.PROCESSED_BUILDS_HISTORY);
            List<String> raw = new ArrayList<>(0);
            if (processed.exists()) {
                raw = Utils.readFileToLines(processed, null);
            }
            if (raw.size() > 0) {
                nvrs.add(raw.get(raw.size() - 1).replaceAll("\\s*#.*", ""));
            }
        }
        context.status(OToolService.OK).result(String.join("\n", nvrs) + "\n");
    });
    get(PROCESSED, context -> {
        String job = context.queryParam(PROCESSED_job);
        if (job != null) {
            try {
                File processed = new File(new File(settings.getJenkinsJobsRoot(), job), Constants.PROCESSED_BUILDS_HISTORY);
                List<String> raw = Utils.readFileToLines(processed, null);
                if (context.queryParam(PROCESSED_cmments) == null) {
                    for (int i = 0; i < raw.size(); i++) {
                        raw.set(i, raw.get(i).replaceAll("\\s*#.*", ""));
                    }
                }
                if (context.queryParam(PROCESSED_uniq) == null) {
                    raw = new ArrayList<>(new TreeSet<>(raw));
                }
                if (context.queryParam(PROCESSED_sort) != null) {
                    Collections.sort(raw);
                // Collections.reverse(raw);no!
                }
                context.status(OToolService.OK).result(String.join("\n", raw) + "\n");
            } catch (IOException e) {
                LOGGER.log(Level.WARNING, e.getMessage(), e);
                context.status(400).result(e.getMessage());
            } catch (Exception e) {
                LOGGER.log(Level.WARNING, e.getMessage(), e);
                context.status(500).result(e.getMessage());
            }
        } else {
            context.status(OToolService.BAD).result("job is mandatory\n");
        }
    });
    get(REDEPLOY_CHECKOUT, context -> {
        try {
            String job = context.queryParam(RERUN_JOB);
            String nvr = context.queryParam(REDEPLOY_NVR);
            String force = context.queryParam("force");
            StringBuilder sb = forceCheckoutOnJob(job, nvr, "true".equals(force));
            context.status(OToolService.OK).result(sb.toString());
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.getMessage(), e);
            context.status(500).result(e.getClass().getName() + ": " + e.getMessage());
        }
    });
    get(RELOAD, context -> {
        try {
            String job = context.queryParam(RERUN_JOB);
            if (job == null) {
                throw new RuntimeException(RERUN_JOB + " is required parameter for " + RELOAD);
            }
            JenkinsCliWrapper.ClientResponse cr = JenkinsCliWrapper.getCli().reloadJob(job);
            try {
                cr.throwIfNecessary();
            } catch (Exception ex) {
                LOGGER.log(Level.WARNING, ex.getMessage(), cr.toString());
                context.status(500).result(ex.getMessage() + ": " + cr.toString());
            }
            context.status(OToolService.OK).result(cr.toString());
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.getMessage(), e);
            context.status(500).result(e.getClass().getName() + ": " + e.getMessage());
        }
    });
    get(REPROVIDER, context -> {
        try {
            String OTOOL_PLATFORM_PROVIDER = JenkinsJobTemplateBuilder.OTOOL_BASH_VAR_PREFIX + JenkinsJobTemplateBuilder.PLATFORM_PROVIDER_VAR;
            List<String> jobs = new RedeployApiWorkerBase.RedeployApiStringListing(context).process(jdkProjectManager, jdkTestProjectManager, parser);
            String doAndHow = context.queryParam(REDEPLOY_DO);
            String nwProvider = context.queryParam(REPROVIDERARG);
            String skipSlaves = context.queryParam(SKIP_SLAVES);
            if (nwProvider == null || nwProvider.trim().isEmpty()) {
                throw new RuntimeException(REPROVIDERARG + " is mandatory\n");
            }
            Set<String> providers = GetterAPI.getProviders(settings.getConfigManager().platformManager);
            if (!providers.contains(nwProvider)) {
                throw new RuntimeException(nwProvider + ": is not valid provider. Use one of: " + String.join(",", providers) + "\n");
            }
            /*
                 * To be able to compute nodes, we need to load nearly everything
                 */
            List<Job> allJobs = new ArrayList<>();
            List<Project> allProjects = new ArrayList<>();
            allProjects.addAll(settings.getConfigManager().jdkProjectManager.readAll());
            allProjects.addAll(settings.getConfigManager().jdkTestProjectManager.readAll());
            for (Project project : allProjects) {
                allJobs.addAll(parser.parse(project));
            }
            StringBuilder sb = new StringBuilder();
            int totalFiles = 0;
            int totalReplacements = 0;
            int invalidNodes = 0;
            final String noneNode = "NoneNodeFound";
            for (String job : jobs) {
                Job foundJob = findJob(allJobs, job);
                sb.append(job).append("\n");
                File jobDir = new File(settings.getJenkinsJobsRoot(), job);
                File config = new File(jobDir, "config.xml");
                List<String> lines = Utils.readFileToLines(config, null);
                for (int i = 0; i < lines.size(); i++) {
                    String mainline = lines.get(i);
                    String[] xmlLines = mainline.split(JenkinsJobTemplateBuilder.XML_NEW_LINE);
                    for (String line : xmlLines) {
                        if (!"true".equals(skipSlaves)) {
                            if (line.contains("<assignedNode>")) {
                                List<OToolVariable> fakeList = new ArrayList<>();
                                JenkinsJobTemplateBuilder.VmWithNodes mWithNodes = null;
                                try {
                                    if (foundJob instanceof TestJob) {
                                        fakeList = Arrays.asList(new OToolVariable("OS_NAME", ((TestJob) foundJob).getPlatform().getOs()));
                                        mWithNodes = JenkinsJobTemplateBuilder.getVmWithNodes(((TestJob) foundJob).getTask(), ((TestJob) foundJob).getPlatform(), new ArrayList<OToolVariable>(), nwProvider);
                                    } else if (foundJob instanceof BuildJob) {
                                        fakeList = Arrays.asList(new OToolVariable("OS_NAME", ((TestJob) foundJob).getPlatform().getOs()));
                                        mWithNodes = JenkinsJobTemplateBuilder.getVmWithNodes(((BuildJob) foundJob).getTask(), ((BuildJob) foundJob).getPlatform(), new ArrayList<OToolVariable>(), nwProvider);
                                    }
                                } catch (Exception ex) {
                                    mWithNodes = new JenkinsJobTemplateBuilder.VmWithNodes("NoNodesForThisCombination", Arrays.asList(noneNode));
                                    invalidNodes++;
                                }
                                String nwVal = "<assignedNode>" + String.join("||", mWithNodes.nodes) + "</assignedNode>";
                                List<String> nvWalToExpand = Arrays.asList(nwVal);
                                String nwValExpanded = JenkinsJobTemplateBuilder.expand(nvWalToExpand, fakeList).get(0);
                                mainline = mainline.replace(line.trim(), nwValExpanded);
                                sb.append(" - " + line.trim() + " -> " + nwValExpanded + "\n");
                                totalReplacements++;
                            }
                        }
                        if (line.contains(OTOOL_PLATFORM_PROVIDER + "=")) {
                            String nwVal = "export " + OTOOL_PLATFORM_PROVIDER + "=" + nwProvider + " # hacked at " + new Date().toString();
                            mainline = mainline.replace(line.trim(), nwVal);
                            sb.append(" - " + line.trim() + " -> " + nwVal + "\n");
                            totalReplacements++;
                        }
                    }
                    lines.set(i, mainline);
                }
                if ("true".equals(doAndHow)) {
                    Utils.writeToFile(config, String.join("\n", lines));
                    sb.append(" - written\n");
                    try {
                        JenkinsCliWrapper.getCli().reloadJob(job).throwIfNecessary();
                        sb.append(" - reloaded\n");
                    } catch (Exception ex) {
                        sb.append(" - reload failed, reload on your own\n");
                    }
                }
                totalFiles++;
            }
            sb.append("true".equals(doAndHow) ? "Written " : "Would be written: " + totalFiles + " of " + jobs.size() + "\n");
            if ("true".equals(skipSlaves)) {
                sb.append("Replaced " + totalReplacements + " of " + jobs.size() + "\n");
            } else {
                sb.append("Replaced " + totalReplacements + " of " + (jobs.size() * 2) + "\n");
            }
            sb.append("Invlaid nodes: " + invalidNodes + "; search for " + noneNode + "\n");
            context.status(OToolService.OK).result(sb.toString() + "\n");
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.getMessage(), e);
            context.status(500).result(e.getClass().getName() + ": " + e.getMessage());
        }
    });
    get(RESLAVES, context -> {
        try {
            List<String> jobs = new RedeployApiWorkerBase.RedeployApiStringListing(context).process(jdkProjectManager, jdkTestProjectManager, parser);
            String doAndHow = context.queryParam(REDEPLOY_DO);
            String nwSlaves = context.queryParam(RESLAVES);
            if (nwSlaves == null || nwSlaves.trim().isEmpty()) {
                throw new RuntimeException(RESLAVES + " is mandatory\n");
            }
            StringBuilder sb = new StringBuilder();
            int totalCountReplacements = 0;
            int totalCountFiles = 0;
            for (String job : jobs) {
                sb.append(job).append("\n");
                File jobDir = new File(settings.getJenkinsJobsRoot(), job);
                File config = new File(jobDir, "config.xml");
                List<String> lines = Utils.readFileToLines(config, null);
                for (int i = 0; i < lines.size(); i++) {
                    String line = lines.get(i);
                    if (line.contains("<assignedNode>")) {
                        String orig = line.trim();
                        String nw = "<assignedNode>" + nwSlaves + "</assignedNode>";
                        sb.append(" - " + orig + " -> " + nw + "\n");
                        lines.set(i, nw);
                        totalCountReplacements++;
                    }
                }
                if ("true".equals(doAndHow)) {
                    Utils.writeToFile(config, String.join("\n", lines));
                    sb.append(" - written\n");
                    try {
                        JenkinsCliWrapper.getCli().reloadJob(job).throwIfNecessary();
                        sb.append(" - reloaded\n");
                    } catch (Exception ex) {
                        sb.append(" - reload failed, reload on your own\n");
                    }
                }
                totalCountFiles++;
            }
            sb.append("true".equals(doAndHow) ? "Written " : "Would be written: " + totalCountFiles + " of " + jobs.size() + "\n");
            sb.append("Replaced " + totalCountReplacements + " of " + jobs.size() + "\n");
            context.status(OToolService.OK).result(sb.toString() + "\n");
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.getMessage(), e);
            context.status(500).result(e.getClass().getName() + ": " + e.getMessage());
        }
    });
    get(REDEPLOY_CHECKOUT_ALL, context -> {
        try {
            List<String> jobs = new RedeployApiWorkerBase.RedeployApiStringListing(context).process(jdkProjectManager, jdkTestProjectManager, parser);
            String doAndHow = context.queryParam(REDEPLOY_DO);
            String nvr = context.queryParam(REDEPLOY_NVR);
            String force = context.queryParam("force");
            if ("true".equals(doAndHow)) {
                List<String> results = new ArrayList<>(jobs.size());
                for (String job : jobs) {
                    try {
                        forceCheckoutOnJob(job, nvr, "true".equals(force));
                        results.add("ok - checking out -  " + job);
                    } catch (Exception ex) {
                        LOGGER.log(Level.WARNING, ex.getMessage(), ex);
                        results.add("failed " + job + ex.toString());
                    }
                }
                context.status(OToolService.OK).result(String.join("\n", results) + "\n");
            } else {
                context.status(OToolService.OK).result(String.join("\n", jobs) + "\n");
            }
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.getMessage(), e);
            context.status(500).result(e.getClass().getName() + ": " + e.getMessage());
        }
    });
    get(REDEPLOY_NOW, context -> {
        try {
            List<String> jobs = new RedeployApiWorkerBase.RedeployApiStringListing(context).process(jdkProjectManager, jdkTestProjectManager, parser);
            String doAndHow = context.queryParam(REDEPLOY_DO);
            if ("true".equals(doAndHow)) {
                List<String> results = new ArrayList<>(jobs.size());
                for (String job : jobs) {
                    try {
                        JenkinsCliWrapper.ClientResponse cr = JenkinsCliWrapper.getCli().scheduleBuild(job);
                        cr.throwIfNecessary();
                        results.add("ok - scheduling -  " + job);
                    } catch (Exception ex) {
                        LOGGER.log(Level.WARNING, ex.getMessage(), ex);
                        results.add("failed " + job + ex.toString());
                    }
                }
                context.status(OToolService.OK).result(String.join("\n", results) + "\n");
            } else {
                context.status(OToolService.OK).result(String.join("\n", jobs) + "\n");
            }
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.getMessage(), e);
            context.status(500).result(e.getClass().getName() + ": " + e.getMessage());
        }
    });
    get(REDEPLOY_RUN, context -> {
        // hmm enable filtering?
        try {
            String job = context.queryParam(RERUN_JOB);
            if (job == null) {
                throw new RuntimeException(RERUN_JOB + " must be an existing job id, was " + job);
            }
            String id = context.queryParam(RERUN_BUILD);
            if (id == null) {
                throw new RuntimeException(RERUN_BUILD + " must be an existing build number, was " + id);
            }
            File currentt = new File(settings.getJenkinsJobsRoot().getAbsolutePath() + File.separator + job + File.separator + "build.xml");
            if (!currentt.getParentFile().exists()) {
                throw new RuntimeException(currentt.getParentFile() + " do not exists. bad job?");
            }
            File archived = new File(settings.getJenkinsJobsRoot().getAbsolutePath() + File.separator + job + File.separator + "builds" + File.separator + id + File.separator + "changelog.xml");
            if (!archived.exists()) {
                throw new RuntimeException(archived.getAbsolutePath() + " do not exists. failed at checkout? Bad id? bad job?");
            }
            StringBuilder sb = new StringBuilder();
            if (!currentt.exists()) {
                sb.append(currentt.getAbsolutePath() + " do not exists. bad job? Broken checkou?t No koji-scm job?\n");
            }
            Files.copy(archived.toPath(), currentt.toPath(), StandardCopyOption.REPLACE_EXISTING);
            sb.append("Copied " + archived.getAbsolutePath() + " as " + currentt.getAbsolutePath() + "\n");
            JenkinsCliWrapper.ClientResponse cr = JenkinsCliWrapper.getCli().scheduleBuild(job);
            cr.throwIfNecessary();
            sb.append("scheduled " + job + "\n");
            context.status(OToolService.OK).result(sb.toString());
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.getMessage(), e);
            context.status(500).result(e.getClass().getName() + ": " + e.getMessage());
        }
    });
    get(REDEPLOY_BUILD, context -> {
        WarHorse wh = new WarHorse(context);
        wh.workload(new NvrDirOperatorFactory(), BuildJob.class);
    });
    get(REDEPLOY_TEST, context -> {
        WarHorse wh = new WarHorse(context);
        wh.workload(new FakeNvrDirOperatorFactory(), TestJob.class);
    });
    get(ARCHES_EXPECTED, context -> {
        try {
            String nvr = context.queryParam(REDEPLOY_NVR);
            if (nvr != null) {
                OToolParser.LegacyNVR nvrParsed = new OToolParser.LegacyNVR(nvr);
                String set = context.queryParam(ARCHES_EXPECTED_SET);
                if (set == null) {
                    File f = new File(settings.getDbFileRoot().toPath().toFile().getAbsolutePath() + "/" + nvrParsed.getFullPath() + "/data");
                    while (f.getParentFile() != null) {
                        File ae = new File(f, FakeBuild.archesConfigFileName);
                        if (ae.exists()) {
                            break;
                        }
                        f = f.getParentFile();
                    }
                    if (f.getParentFile() == null) {
                        context.status(OToolService.OK).result("No " + FakeBuild.archesConfigFileName + " for " + nvr + " arches expected are old api only!\n");
                    } else {
                        File ae = new File(f, FakeBuild.archesConfigFileName);
                        // by luck, same comments schema is used in processed.txt and arches.expected
                        List<String> archesWithoutCommenrs = Utils.readProcessedTxt(ae);
                        if (ae.length() < 4 || archesWithoutCommenrs.isEmpty()) {
                            context.status(OToolService.BAD).result(ae.getAbsolutePath() + " is emmpty or very small. That will break a lot of stuff!\n");
                        } else {
                            context.status(OToolService.OK).result(String.join(" ", archesWithoutCommenrs.get(0)) + " (" + ae.getAbsolutePath() + ")\n");
                        }
                    }
                } else {
                    File mainPath = new File(settings.getDbFileRoot().toPath().toFile().getAbsolutePath() + "/" + nvrParsed.getFullPath());
                    if (!mainPath.exists()) {
                        context.status(OToolService.BAD).result(mainPath.getAbsolutePath() + " Do not exists. Invlid NVRos?\n");
                    } else {
                        File data = new File(mainPath, "data");
                        File mainFile = new File(data, FakeBuild.archesConfigFileName);
                        if (mainFile.exists()) {
                            List<String> archesWithoutCommenrs = Utils.readProcessedTxt(mainFile);
                            FakeBuild.generateDefaultArchesFile(mainFile, set);
                            if (archesWithoutCommenrs.isEmpty()) {
                                context.status(OToolService.OK).result("overwritten " + mainFile + " (was: empty, is`" + set + "`)\n");
                            } else {
                                context.status(OToolService.OK).result("overwritten " + mainFile + " (was: `" + archesWithoutCommenrs.get(0) + "`, is`" + set + "`)\n");
                            }
                        } else {
                            data.mkdirs();
                            FakeBuild.generateDefaultArchesFile(mainFile, set);
                            context.status(OToolService.OK).result("written " + mainFile + "  (is`" + set + "`)\n");
                        }
                    }
                }
            } else {
                ArchesExpectedWorker aw = new ArchesExpectedWorker();
                aw.prepare();
                List<Platform> platforms = platformManager.readAll();
                Set<String> kojiArches = new HashSet<>();
                for (Platform p : platforms) {
                    kojiArches.add(p.getKojiArch().orElse(p.getArchitecture()));
                }
                // filtr affected jobs + places in builds (s neb arches>
                context.status(OToolService.OK).result(aw.dirsWithArches.entrySet().stream().map((Function<Map.Entry<String, String[]>, String>) e -> String.join(" ", e.getValue()) + " (" + e.getKey() + ")").sorted().collect(Collectors.joining("\n")) + "\n" + "All used: " + aw.usedArches.stream().collect(Collectors.joining(" ")) + "\n" + "All possible: " + kojiArches.stream().collect(Collectors.joining(" ")) + "\n");
            // better to filter them up rather then here
            }
        } catch (StorageException | IOException e) {
            LOGGER.log(Level.WARNING, e.getMessage(), e);
            context.status(400).result(e.getMessage());
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.getMessage(), e);
            context.status(500).result(e.getMessage());
        }
    });
}
Also used : MISC(org.fakekoji.api.http.rest.OToolService.MISC) Arrays(java.util.Arrays) Date(java.util.Date) TaskVariantManager(org.fakekoji.jobmanager.manager.TaskVariantManager) Utils(org.fakekoji.Utils) JDKTestProject(org.fakekoji.jobmanager.model.JDKTestProject) PlatformManager(org.fakekoji.jobmanager.manager.PlatformManager) Context(io.javalin.http.Context) Map(java.util.Map) StorageException(org.fakekoji.storage.StorageException) BuildJob(org.fakekoji.jobmanager.model.BuildJob) JavaServerConstants(org.fakekoji.xmlrpc.server.JavaServerConstants) Path(java.nio.file.Path) JDKVersionManager(org.fakekoji.jobmanager.manager.JDKVersionManager) Project(org.fakekoji.jobmanager.model.Project) FileVisitor(java.nio.file.FileVisitor) VariantsConfig(org.fakekoji.jobmanager.model.VariantsConfig) Set(java.util.Set) BuildPlatformConfig(org.fakekoji.jobmanager.model.BuildPlatformConfig) Logger(java.util.logging.Logger) EndpointGroup(io.javalin.apibuilder.EndpointGroup) JDKProject(org.fakekoji.jobmanager.model.JDKProject) Collectors(java.util.stream.Collectors) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) OToolBuild(org.fakekoji.model.OToolBuild) Result(org.fakekoji.functional.Result) ApiBuilder.get(io.javalin.apibuilder.ApiBuilder.get) NotNull(org.jetbrains.annotations.NotNull) JenkinsCliWrapper(org.fakekoji.jobmanager.JenkinsCliWrapper) Platform(org.fakekoji.model.Platform) Tuple(org.fakekoji.functional.Tuple) JDKTestProjectManager(org.fakekoji.jobmanager.project.JDKTestProjectManager) Job(org.fakekoji.jobmanager.model.Job) HashMap(java.util.HashMap) JDKProjectParser(org.fakekoji.jobmanager.project.JDKProjectParser) Function(java.util.function.Function) TreeSet(java.util.TreeSet) OToolVariable(org.fakekoji.model.OToolVariable) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) ConfigManager(org.fakekoji.jobmanager.ConfigManager) RedeployApiWorkerBase(org.fakekoji.api.http.rest.utils.RedeployApiWorkerBase) Constants(hudson.plugins.scm.koji.Constants) TestJobConfiguration(org.fakekoji.jobmanager.model.TestJobConfiguration) ManagementException(org.fakekoji.jobmanager.ManagementException) Files(java.nio.file.Files) JenkinsJobTemplateBuilder(org.fakekoji.jobmanager.JenkinsJobTemplateBuilder) FakeBuild(org.fakekoji.core.FakeBuild) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) File(java.io.File) OToolParser(org.fakekoji.core.utils.OToolParser) TestJob(org.fakekoji.jobmanager.model.TestJob) JDKProjectManager(org.fakekoji.jobmanager.project.JDKProjectManager) Comparator(java.util.Comparator) Collections(java.util.Collections) AccessibleSettings(org.fakekoji.core.AccessibleSettings) TestJob(org.fakekoji.jobmanager.model.TestJob) Platform(org.fakekoji.model.Platform) ArrayList(java.util.ArrayList) JenkinsJobTemplateBuilder(org.fakekoji.jobmanager.JenkinsJobTemplateBuilder) TreeSet(java.util.TreeSet) OToolVariable(org.fakekoji.model.OToolVariable) BuildJob(org.fakekoji.jobmanager.model.BuildJob) BuildJob(org.fakekoji.jobmanager.model.BuildJob) Job(org.fakekoji.jobmanager.model.Job) TestJob(org.fakekoji.jobmanager.model.TestJob) HashSet(java.util.HashSet) OToolParser(org.fakekoji.core.utils.OToolParser) IOException(java.io.IOException) StorageException(org.fakekoji.storage.StorageException) ManagementException(org.fakekoji.jobmanager.ManagementException) IOException(java.io.IOException) Date(java.util.Date) JDKTestProject(org.fakekoji.jobmanager.model.JDKTestProject) Project(org.fakekoji.jobmanager.model.Project) JDKProject(org.fakekoji.jobmanager.model.JDKProject) JenkinsCliWrapper(org.fakekoji.jobmanager.JenkinsCliWrapper) RedeployApiWorkerBase(org.fakekoji.api.http.rest.utils.RedeployApiWorkerBase) File(java.io.File) StorageException(org.fakekoji.storage.StorageException)

Example 7 with Context

use of io.javalin.http.Context in project AuthGuard by AuthGuard.

the class AccountsRoute method create.

public void create(final Context context) {
    final String idempotentKey = IdempotencyHeader.getKeyOrFail(context);
    final CreateAccountRequestDTO request = accountRequestBodyHandler.getValidated(context);
    if (!canPerform(context, request)) {
        context.status(403).json(new Error("", "An auth client violated its restrictions in the request"));
        return;
    }
    final RequestContextBO requestContext = RequestContextBO.builder().idempotentKey(idempotentKey).source(context.ip()).build();
    final Optional<AccountDTO> createdAccount = Optional.of(restMapper.toBO(request)).map(accountBO -> accountsService.create(accountBO, requestContext)).map(restMapper::toDTO);
    if (createdAccount.isPresent()) {
        context.status(201).json(createdAccount.get());
    } else {
        context.status(400).json(new Error("400", "Failed to create account"));
    }
}
Also used : Inject(com.google.inject.Inject) IdempotencyException(com.nexblocks.authguard.service.exceptions.IdempotencyException) CredentialsService(com.nexblocks.authguard.service.CredentialsService) com.nexblocks.authguard.api.dto.requests(com.nexblocks.authguard.api.dto.requests) AccountsService(com.nexblocks.authguard.service.AccountsService) RestMapper(com.nexblocks.authguard.rest.mappers.RestMapper) Context(io.javalin.http.Context) ActorDomainVerifier(com.nexblocks.authguard.rest.access.ActorDomainVerifier) AccountsApi(com.nexblocks.authguard.api.routes.AccountsApi) IdempotencyHeader(com.nexblocks.authguard.rest.util.IdempotencyHeader) ApplicationsService(com.nexblocks.authguard.service.ApplicationsService) AccountLocksService(com.nexblocks.authguard.service.AccountLocksService) AccountDTO(com.nexblocks.authguard.api.dto.entities.AccountDTO) AppDTO(com.nexblocks.authguard.api.dto.entities.AppDTO) ErrorCode(com.nexblocks.authguard.service.exceptions.codes.ErrorCode) Collection(java.util.Collection) CompletionException(java.util.concurrent.CompletionException) com.nexblocks.authguard.service.model(com.nexblocks.authguard.service.model) AuthGuardRoles(com.nexblocks.authguard.api.access.AuthGuardRoles) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) BodyHandler(com.nexblocks.authguard.rest.util.BodyHandler) Error(com.nexblocks.authguard.api.dto.entities.Error) AccountLockDTO(com.nexblocks.authguard.api.dto.entities.AccountLockDTO) Optional(java.util.Optional) Error(com.nexblocks.authguard.api.dto.entities.Error) AccountDTO(com.nexblocks.authguard.api.dto.entities.AccountDTO)

Example 8 with Context

use of io.javalin.http.Context in project AuthGuard by AuthGuard.

the class AccountsRoute method createComplete.

@Override
public void createComplete(final Context context) {
    final String idempotentKey = IdempotencyHeader.getKeyOrFail(context);
    final CreateCompleteAccountRequestDTO request = completeAccountRequestBodyHandler.getValidated(context);
    if (!canPerform(context, request.getAccount())) {
        context.status(403).json(new Error("", "An auth client violated its restrictions in the request"));
        return;
    }
    final RequestContextBO requestContext = RequestContextBO.builder().idempotentKey(idempotentKey).source(context.ip()).build();
    final AccountBO accountBO = restMapper.toBO(request.getAccount());
    final CredentialsBO credentialsBO = restMapper.toBO(request.getCredentials());
    final List<UserIdentifierBO> identifiers = credentialsBO.getIdentifiers().stream().map(identifier -> identifier.withDomain(credentialsBO.getDomain())).collect(Collectors.toList());
    String accountId;
    String credentialsId;
    try {
        accountId = accountsService.create(accountBO, requestContext).getId();
    } catch (final CompletionException e) {
        if (e.getCause() instanceof IdempotencyException) {
            accountId = ((IdempotencyException) e.getCause()).getIdempotentRecord().getEntityId();
        } else {
            throw e;
        }
    }
    try {
        final CredentialsBO withAdditionalInfo = CredentialsBO.builder().from(credentialsBO).identifiers(identifiers).accountId(accountId).build();
        credentialsId = credentialsService.create(withAdditionalInfo, requestContext).getId();
    } catch (final CompletionException e) {
        if (e.getCause() instanceof IdempotencyException) {
            credentialsId = ((IdempotencyException) e.getCause()).getIdempotentRecord().getEntityId();
        } else {
            throw e;
        }
    }
    final CreateCompleteAccountResponseDTO response = CreateCompleteAccountResponseDTO.builder().accountId(accountId).credentialsId(credentialsId).build();
    context.status(201).json(response);
}
Also used : Inject(com.google.inject.Inject) IdempotencyException(com.nexblocks.authguard.service.exceptions.IdempotencyException) CredentialsService(com.nexblocks.authguard.service.CredentialsService) com.nexblocks.authguard.api.dto.requests(com.nexblocks.authguard.api.dto.requests) AccountsService(com.nexblocks.authguard.service.AccountsService) RestMapper(com.nexblocks.authguard.rest.mappers.RestMapper) Context(io.javalin.http.Context) ActorDomainVerifier(com.nexblocks.authguard.rest.access.ActorDomainVerifier) AccountsApi(com.nexblocks.authguard.api.routes.AccountsApi) IdempotencyHeader(com.nexblocks.authguard.rest.util.IdempotencyHeader) ApplicationsService(com.nexblocks.authguard.service.ApplicationsService) AccountLocksService(com.nexblocks.authguard.service.AccountLocksService) AccountDTO(com.nexblocks.authguard.api.dto.entities.AccountDTO) AppDTO(com.nexblocks.authguard.api.dto.entities.AppDTO) ErrorCode(com.nexblocks.authguard.service.exceptions.codes.ErrorCode) Collection(java.util.Collection) CompletionException(java.util.concurrent.CompletionException) com.nexblocks.authguard.service.model(com.nexblocks.authguard.service.model) AuthGuardRoles(com.nexblocks.authguard.api.access.AuthGuardRoles) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) BodyHandler(com.nexblocks.authguard.rest.util.BodyHandler) Error(com.nexblocks.authguard.api.dto.entities.Error) AccountLockDTO(com.nexblocks.authguard.api.dto.entities.AccountLockDTO) Optional(java.util.Optional) CompletionException(java.util.concurrent.CompletionException) IdempotencyException(com.nexblocks.authguard.service.exceptions.IdempotencyException) Error(com.nexblocks.authguard.api.dto.entities.Error)

Example 9 with Context

use of io.javalin.http.Context in project cwms-radar-api by USACE.

the class TimeSeriesControllerTest method testDaoMock.

@Test
public void testDaoMock() throws JsonProcessingException {
    String officeId = "LRL";
    String tsId = "RYAN3.Stage.Inst.5Minutes.0.ZSTORE_TS_TEST";
    TimeSeries expected = buildTimeSeries(officeId, tsId);
    // build a mock dao that returns a pre-built ts when called a certain way
    TimeSeriesDao dao = mock(TimeSeriesDao.class);
    when(dao.getTimeseries(eq(""), eq(500), eq(tsId), eq(officeId), eq("EN"), isNull(), isNotNull(), isNotNull(), isNotNull())).thenReturn(expected);
    // build mock request and response
    final HttpServletRequest request = mock(HttpServletRequest.class);
    final HttpServletResponse response = mock(HttpServletResponse.class);
    final Map<String, ?> map = new LinkedHashMap<>();
    when(request.getAttribute("office-id")).thenReturn(officeId);
    when(request.getAttribute("database")).thenReturn(null);
    when(request.getHeader(Header.ACCEPT)).thenReturn(Formats.JSONV2);
    Map<String, String> urlParams = new LinkedHashMap<>();
    urlParams.put("office", officeId);
    urlParams.put("name", tsId);
    String paramStr = buildParamStr(urlParams);
    when(request.getQueryString()).thenReturn(paramStr);
    when(request.getRequestURL()).thenReturn(new StringBuffer("http://127.0.0.1:7001/timeseries"));
    // build real context that uses the mock request/response
    Context ctx = new Context(request, response, map);
    // Build a controller that doesn't actually talk to database
    TimeSeriesController controller = new TimeSeriesController(new MetricRegistry()) {

        @Override
        protected DSLContext getDslContext(Context ctx) {
            return null;
        }

        @NotNull
        @Override
        protected TimeSeriesDao getTimeSeriesDao(DSLContext dsl) {
            return dao;
        }
    };
    // make controller use our mock dao
    // Do a controller getAll with our context
    controller.getAll(ctx);
    // Check that the controller accessed our mock dao in the expected way
    verify(dao, times(1)).getTimeseries(eq(""), eq(500), eq(tsId), eq(officeId), eq("EN"), isNull(), isNotNull(), isNotNull(), isNotNull());
    // Make sure controller thought it was happy
    verify(response).setStatus(200);
    // And make sure controller returned json
    verify(response).setContentType(Formats.JSONV2);
    String result = ctx.resultString();
    // MAke sure we got some sort of response
    assertNotNull(result);
    // Turn json response back into a TimeSeries object
    ObjectMapper om = JsonV2.buildObjectMapper();
    TimeSeries actual = om.readValue(result, TimeSeries.class);
    assertSimilar(expected, actual);
}
Also used : Context(io.javalin.http.Context) DSLContext(org.jooq.DSLContext) TimeSeries(cwms.radar.data.dto.TimeSeries) MetricRegistry(com.codahale.metrics.MetricRegistry) HttpServletResponse(javax.servlet.http.HttpServletResponse) DSLContext(org.jooq.DSLContext) LinkedHashMap(java.util.LinkedHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) TimeSeriesDao(cwms.radar.data.dao.TimeSeriesDao) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.jupiter.api.Test)

Example 10 with Context

use of io.javalin.http.Context in project cwms-radar-api by USACE.

the class CatalogControllerTest method bad_formats_return_501.

// get all the infrastructure in place first.
@Disabled
@ParameterizedTest
@ValueSource(strings = { "blurge,", "appliation/json+fred" })
public void bad_formats_return_501(String format) throws Exception {
    final String testBody = "test";
    CatalogController controller = spy(new CatalogController(new MetricRegistry()));
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    HashMap<String, Object> attributes = new HashMap<>();
    attributes.put(ContextUtil.maxRequestSizeKey, Integer.MAX_VALUE);
    when(request.getInputStream()).thenReturn(new TestServletInputStream(testBody));
    when(request.getAttribute("database")).thenReturn(this.conn);
    when(request.getRequestURI()).thenReturn("/catalog/TIMESERIES");
    Context context = ContextUtil.init(request, response, "*", new HashMap<String, String>(), HandlerType.GET, attributes);
    context.attribute("database", this.conn);
    assertNotNull(context.attribute("database"), "could not get the connection back as an attribute");
    when(request.getHeader(Header.ACCEPT)).thenReturn("BAD FORMAT");
    assertThrows(FormattingException.class, () -> {
        controller.getAll(context);
    });
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Context(io.javalin.http.Context) HashMap(java.util.HashMap) MetricRegistry(com.codahale.metrics.MetricRegistry) HttpServletResponse(javax.servlet.http.HttpServletResponse) TestHttpServletResponse(fixtures.TestHttpServletResponse) TestServletInputStream(fixtures.TestServletInputStream) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Disabled(org.junit.jupiter.api.Disabled)

Aggregations

Context (io.javalin.http.Context)22 List (java.util.List)13 Optional (java.util.Optional)10 Map (java.util.Map)9 Collectors (java.util.stream.Collectors)9 HashMap (java.util.HashMap)7 MetricRegistry (com.codahale.metrics.MetricRegistry)6 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 Handler (io.javalin.http.Handler)5 HttpMethod (io.javalin.plugin.openapi.annotations.HttpMethod)5 OpenApi (io.javalin.plugin.openapi.annotations.OpenApi)5 OpenApiContent (io.javalin.plugin.openapi.annotations.OpenApiContent)5 OpenApiResponse (io.javalin.plugin.openapi.annotations.OpenApiResponse)5 Inject (com.google.inject.Inject)4 Error (com.nexblocks.authguard.api.dto.entities.Error)4 RestMapper (com.nexblocks.authguard.rest.mappers.RestMapper)4 BodyHandler (com.nexblocks.authguard.rest.util.BodyHandler)4 IdempotencyHeader (com.nexblocks.authguard.rest.util.IdempotencyHeader)4 TestServletInputStream (fixtures.TestServletInputStream)3