Search in sources :

Example 6 with Question

use of org.batfish.datamodel.questions.Question in project batfish by batfish.

the class WorkMgrServiceTest method getQuestionTemplates.

@Test
public void getQuestionTemplates() throws Exception {
    initContainerEnvironment();
    Question testQuestion = createTestQuestion("testquestion", "test description");
    ObjectMapper mapper = BatfishObjectMapper.mapper();
    // serializing the question in the temp questions folder
    String questionJsonString = mapper.writeValueAsString(testQuestion);
    CommonUtil.writeFile(_questionsTemplatesFolder.newFile("testQuestion.json").toPath(), questionJsonString);
    JSONArray questionsResponse = _service.getQuestionTemplates(CoordConsts.DEFAULT_API_KEY);
    // testting if the response is valid and contains testquestion
    if (questionsResponse.get(0).equals(CoordConsts.SVC_KEY_SUCCESS)) {
        JSONObject questionsJsonObject = (JSONObject) questionsResponse.get(1);
        String questionsJsonString = questionsJsonObject.getString(CoordConsts.SVC_KEY_QUESTION_LIST);
        Map<String, String> questionsMap = mapper.readValue(questionsJsonString, new TypeReference<Map<String, String>>() {
        });
        if (questionsMap.containsKey("testquestion")) {
            assertThat(questionsMap.get("testquestion"), is(equalTo(questionJsonString)));
        } else {
            fail("Question not found in the response");
        }
    } else {
        fail("Service call was not successful");
    }
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) JSONArray(org.codehaus.jettison.json.JSONArray) Question(org.batfish.datamodel.questions.Question) Map(java.util.Map) BatfishObjectMapper(org.batfish.common.util.BatfishObjectMapper) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 7 with Question

use of org.batfish.datamodel.questions.Question in project batfish by batfish.

the class WorkMgr method computeWorkDetails.

private WorkDetails computeWorkDetails(WorkItem workItem) {
    WorkType workType = WorkType.UNKNOWN;
    if (WorkItemBuilder.isParsingWorkItem(workItem)) {
        workType = WorkType.PARSING;
    }
    if (WorkItemBuilder.isDataplaningWorkItem(workItem)) {
        if (workType != WorkType.UNKNOWN) {
            throw new BatfishException("Cannot do composite work. Separate PARSING and DATAPLANING.");
        }
        workType = WorkType.DATAPLANING;
    }
    if (WorkItemBuilder.isAnsweringWorkItem(workItem)) {
        if (workType != WorkType.UNKNOWN) {
            throw new BatfishException("Cannot do composite work. Separate ANSWER from other work.");
        }
        String qName = WorkItemBuilder.getQuestionName(workItem);
        if (qName == null) {
            throw new BatfishException("Question name not provided for ANSWER work");
        }
        Path qFile = getpathContainerQuestion(workItem.getContainerName(), qName);
        Question question = Question.parseQuestion(qFile);
        workType = question.getIndependent() ? WorkType.INDEPENDENT_ANSWERING : question.getDataPlane() ? WorkType.DATAPLANE_DEPENDENT_ANSWERING : WorkType.PARSING_DEPENDENT_ANSWERING;
    }
    if (WorkItemBuilder.isAnalyzingWorkItem(workItem)) {
        if (workType != WorkType.UNKNOWN) {
            throw new BatfishException("Cannot do composite work. Separate ANALYZE from other work.");
        }
        String aName = WorkItemBuilder.getAnalysisName(workItem);
        if (aName == null) {
            throw new BatfishException("Analysis name not provided for ANALYZE work");
        }
        Set<String> qNames = listAnalysisQuestions(workItem.getContainerName(), aName);
        // compute the strongest dependency among the embedded questions
        workType = WorkType.INDEPENDENT_ANSWERING;
        for (String qName : qNames) {
            Path qFile = getpathAnalysisQuestion(workItem.getContainerName(), aName, qName);
            Question question = Question.parseQuestion(qFile);
            if (question.getDataPlane()) {
                workType = WorkType.DATAPLANE_DEPENDENT_ANSWERING;
                break;
            }
            if (!question.getIndependent()) {
                workType = WorkType.PARSING_DEPENDENT_ANSWERING;
            }
        }
    }
    Pair<Pair<String, String>, Pair<String, String>> settings = WorkItemBuilder.getBaseAndDeltaSettings(workItem);
    WorkDetails details = new WorkDetails(WorkItemBuilder.getBaseTestrig(settings), WorkItemBuilder.getBaseEnvironment(settings), WorkItemBuilder.getDeltaTestrig(settings), WorkItemBuilder.getDeltaEnvironment(settings), WorkItemBuilder.isDifferential(workItem), workType);
    return details;
}
Also used : Path(java.nio.file.Path) BatfishException(org.batfish.common.BatfishException) WorkType(org.batfish.coordinator.WorkDetails.WorkType) Question(org.batfish.datamodel.questions.Question) Pair(org.batfish.common.Pair)

Example 8 with Question

use of org.batfish.datamodel.questions.Question in project batfish by batfish.

the class WorkMgrService method configureQuestionTemplate.

/**
 * Add/replace exceptions and assertions to question template
 *
 * @param apiKey The API key of the client
 * @param clientVersion The version of the client
 * @param questionTemplate The template to extend (JSON string)
 * @param exceptions The exceptions to add (JSON string)
 * @param assertion The assertions to add (JSON string)
 * @return packages the JSON of the resulting template
 */
@POST
@Path(CoordConsts.SVC_RSC_CONFIGURE_QUESTION_TEMPLATE)
@Produces(MediaType.APPLICATION_JSON)
public JSONArray configureQuestionTemplate(@FormDataParam(CoordConsts.SVC_KEY_API_KEY) String apiKey, @FormDataParam(CoordConsts.SVC_KEY_VERSION) String clientVersion, @FormDataParam(CoordConsts.SVC_KEY_QUESTION) String questionTemplate, @Nullable @FormDataParam(CoordConsts.SVC_KEY_EXCEPTIONS) String exceptions, @Nullable @FormDataParam(CoordConsts.SVC_KEY_ASSERTION) String assertion) {
    try {
        _logger.infof("WMS:configureQuestionTemplate: q: %s e: %s a: %s\n", questionTemplate, exceptions, assertion);
        checkStringParam(apiKey, "API key");
        checkStringParam(clientVersion, "Client version");
        checkStringParam(questionTemplate, "Question template");
        checkApiKeyValidity(apiKey);
        checkClientVersion(clientVersion);
        Question inputQuestion = Question.parseQuestion(questionTemplate);
        Question outputQuestion = inputQuestion.configureTemplate(exceptions, assertion);
        String outputQuestionStr = BatfishObjectMapper.writePrettyString(outputQuestion);
        return successResponse(new JSONObject().put(CoordConsts.SVC_KEY_QUESTION, outputQuestionStr));
    } catch (IllegalArgumentException | AccessControlException e) {
        _logger.errorf("WMS:getWorkStatus exception: %s\n", e.getMessage());
        return failureResponse(e.getMessage());
    } catch (Exception e) {
        String stackTrace = ExceptionUtils.getStackTrace(e);
        _logger.errorf("WMS:getWorkStatus exception: %s", stackTrace);
        return failureResponse(e.getMessage());
    }
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) AccessControlException(java.security.AccessControlException) Question(org.batfish.datamodel.questions.Question) BatfishException(org.batfish.common.BatfishException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) FileExistsException(org.apache.commons.io.FileExistsException) AccessControlException(java.security.AccessControlException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 9 with Question

use of org.batfish.datamodel.questions.Question in project batfish by batfish.

the class Main method readQuestionTemplate.

private static String readQuestionTemplate(Path file, Map<String, String> templates) {
    String questionText = CommonUtil.readFile(file);
    try {
        JSONObject questionObj = new JSONObject(questionText);
        if (questionObj.has(BfConsts.PROP_INSTANCE) && !questionObj.isNull(BfConsts.PROP_INSTANCE)) {
            JSONObject instanceDataObj = questionObj.getJSONObject(BfConsts.PROP_INSTANCE);
            String instanceDataStr = instanceDataObj.toString();
            Question.InstanceData instanceData = BatfishObjectMapper.mapper().readValue(instanceDataStr, Question.InstanceData.class);
            String name = instanceData.getInstanceName();
            if (templates.containsKey(name)) {
                throw new BatfishException("Duplicate template name " + name);
            }
            templates.put(name.toLowerCase(), questionText);
            return name;
        } else {
            throw new BatfishException("Question in file: '" + file + "' has no instance name");
        }
    } catch (JSONException | IOException e) {
        throw new BatfishException("Failed to process question", e);
    }
}
Also used : BatfishException(org.batfish.common.BatfishException) JSONObject(org.codehaus.jettison.json.JSONObject) JSONException(org.codehaus.jettison.json.JSONException) Question(org.batfish.datamodel.questions.Question) IOException(java.io.IOException)

Example 10 with Question

use of org.batfish.datamodel.questions.Question in project batfish by batfish.

the class Client method answerType.

private boolean answerType(String questionType, String paramsLine, boolean isDelta, FileWriter outWriter) {
    JSONObject questionJson;
    try {
        String questionString = QuestionHelper.getQuestionString(questionType, _questions, false);
        questionJson = new JSONObject(questionString);
        Map<String, JsonNode> parameters = parseParams(paramsLine);
        for (Entry<String, JsonNode> e : parameters.entrySet()) {
            String parameterName = e.getKey();
            String parameterValue = e.getValue().toString();
            Object parameterObj;
            try {
                parameterObj = new JSONTokener(parameterValue.toString()).nextValue();
                questionJson.put(parameterName, parameterObj);
            } catch (JSONException e1) {
                throw new BatfishException("Failed to apply parameter: '" + parameterName + "' with value: '" + parameterValue + "' to question JSON", e1);
            }
        }
    } catch (JSONException e) {
        throw new BatfishException("Failed to convert unmodified question string to JSON", e);
    } catch (BatfishException e) {
        _logger.errorf("Could not construct a question: %s\n", e.getMessage());
        return false;
    }
    String modifiedQuestionJson = questionJson.toString();
    Question modifiedQuestion = null;
    try {
        modifiedQuestion = BatfishObjectMapper.mapper().readValue(modifiedQuestionJson, Question.class);
    } catch (IOException e) {
        throw new BatfishException("Modified question is no longer valid, likely due to invalid parameters", e);
    }
    if (modifiedQuestion.getDifferential() && (_currDeltaEnv == null || _currDeltaTestrig == null)) {
        _logger.output(DIFF_NOT_READY_MSG);
        return false;
    }
    // if no exception is thrown, then the modifiedQuestionJson is good
    Path questionFile = createTempFile("question", modifiedQuestionJson);
    questionFile.toFile().deleteOnExit();
    boolean result = answerFile(questionFile, modifiedQuestion.getDifferential(), isDelta, outWriter);
    if (questionFile != null) {
        CommonUtil.deleteIfExists(questionFile);
    }
    return result;
}
Also used : Path(java.nio.file.Path) BatfishException(org.batfish.common.BatfishException) JSONException(org.codehaus.jettison.json.JSONException) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) JSONTokener(org.codehaus.jettison.json.JSONTokener) JSONObject(org.codehaus.jettison.json.JSONObject) JSONObject(org.codehaus.jettison.json.JSONObject) Question(org.batfish.datamodel.questions.Question)

Aggregations

Question (org.batfish.datamodel.questions.Question)10 BatfishException (org.batfish.common.BatfishException)6 JSONObject (org.codehaus.jettison.json.JSONObject)5 IOException (java.io.IOException)4 Path (java.nio.file.Path)2 Map (java.util.Map)2 IBatfish (org.batfish.common.plugin.IBatfish)2 AnswerElement (org.batfish.datamodel.answers.AnswerElement)2 JSONException (org.codehaus.jettison.json.JSONException)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 ActiveSpan (io.opentracing.ActiveSpan)1 FileNotFoundException (java.io.FileNotFoundException)1 AccessControlException (java.security.AccessControlException)1 Set (java.util.Set)1 SortedSet (java.util.SortedSet)1 TreeSet (java.util.TreeSet)1 ExecutionException (java.util.concurrent.ExecutionException)1