Search in sources :

Example 6 with BatfishException

use of org.batfish.common.BatfishException in project batfish by batfish.

the class Client method createTempFile.

private Path createTempFile(String filePrefix, String content) {
    Path tempFilePath;
    try {
        tempFilePath = Files.createTempFile(filePrefix, null);
    } catch (IOException e) {
        throw new BatfishException("Failed to create temporary file", e);
    }
    File tempFile = tempFilePath.toFile();
    tempFile.deleteOnExit();
    _logger.debugf("Creating temporary %s file: %s\n", filePrefix, tempFilePath.toAbsolutePath());
    FileWriter writer;
    try {
        writer = new FileWriter(tempFile);
        writer.write(content + "\n");
        writer.close();
    } catch (IOException e) {
        throw new BatfishException("Failed to write content to temporary file", e);
    }
    return tempFilePath;
}
Also used : Path(java.nio.file.Path) BatfishException(org.batfish.common.BatfishException) FileWriter(java.io.FileWriter) IOException(java.io.IOException) File(java.io.File)

Example 7 with BatfishException

use of org.batfish.common.BatfishException in project batfish by batfish.

the class Client method loadQuestionsFromDir.

/**
 * Loads questions from a local directory containing questions
 *
 * @param questionsPathStr Path of directory
 * @return loadedQuestions {@link Multimap} containing loaded question names and content
 * @throws BatfishException if loading of any of the question is not successful or if cannot walk
 *     the directory provided
 */
static Multimap<String, String> loadQuestionsFromDir(String questionsPathStr) {
    Path questionsPath = Paths.get(questionsPathStr);
    SortedSet<Path> jsonQuestionFiles = new TreeSet<>();
    try {
        Files.walkFileTree(questionsPath, EnumSet.of(FOLLOW_LINKS), 1, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                String filename = file.getFileName().toString();
                if (filename.endsWith(".json")) {
                    jsonQuestionFiles.add(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new BatfishException("Failed to visit questions dir", e);
    }
    Multimap<String, String> loadedQuestions = HashMultimap.create();
    for (Path jsonQuestionFile : jsonQuestionFiles) {
        JSONObject questionJSON = loadQuestionFromFile(jsonQuestionFile);
        loadedQuestions.put(getQuestionName(questionJSON, jsonQuestionFile.toString()), questionJSON.toString());
    }
    return loadedQuestions;
}
Also used : Path(java.nio.file.Path) BatfishException(org.batfish.common.BatfishException) JSONObject(org.codehaus.jettison.json.JSONObject) TreeSet(java.util.TreeSet) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 8 with BatfishException

use of org.batfish.common.BatfishException in project batfish by batfish.

the class Client method parseInitEnvironmentParams.

static InitEnvironmentParams parseInitEnvironmentParams(String paramsLine) {
    String jsonParamsStr = "{ " + paramsLine + " }";
    InitEnvironmentParams parameters;
    try {
        parameters = BatfishObjectMapper.mapper().readValue(new JSONObject(jsonParamsStr).toString(), new TypeReference<InitEnvironmentParams>() {
        });
        return parameters;
    } catch (JSONException | IOException e) {
        throw new BatfishException("Failed to parse parameters. (Are all key-value pairs separated by commas? Are all " + "values valid JSON?)", e);
    }
}
Also used : BatfishException(org.batfish.common.BatfishException) JSONObject(org.codehaus.jettison.json.JSONObject) JSONException(org.codehaus.jettison.json.JSONException) InitEnvironmentParams(org.batfish.client.params.InitEnvironmentParams) TypeReference(com.fasterxml.jackson.core.type.TypeReference) IOException(java.io.IOException)

Example 9 with BatfishException

use of org.batfish.common.BatfishException in project batfish by batfish.

the class Client method pollWorkAndGetAnswer.

private boolean pollWorkAndGetAnswer(WorkItem wItem, @Nullable FileWriter outWriter) {
    boolean pollResult = pollWork(wItem.getId(), outWriter);
    if (!pollResult) {
        return false;
    }
    // get the answer
    String ansFileName = wItem.getId() + BfConsts.SUFFIX_ANSWER_JSON_FILE;
    String downloadedAnsFile = _workHelper.getObject(wItem.getContainerName(), wItem.getTestrigName(), ansFileName);
    if (downloadedAnsFile == null) {
        _logger.errorf("Failed to get answer file %s. (Was work killed?)\n", ansFileName);
    } else {
        String answerString = CommonUtil.readFile(Paths.get(downloadedAnsFile));
        // Check if we need to make things pretty
        // Don't if we are writing to FileWriter, because we need valid JSON in
        // that case
        String answerStringToPrint = answerString;
        if (outWriter == null && _settings.getPrettyPrintAnswers()) {
            Answer answer;
            try {
                answer = BatfishObjectMapper.mapper().readValue(answerString, Answer.class);
            } catch (IOException e) {
                throw new BatfishException("Response does not appear to be valid JSON representation of " + Answer.class.getSimpleName(), e);
            }
            answerStringToPrint = answer.prettyPrint();
        }
        logOutput(outWriter, answerStringToPrint);
        // tests serialization/deserialization when running in debug mode
        if (_logger.getLogLevel() >= BatfishLogger.LEVEL_DEBUG) {
            try {
                ObjectMapper reader = BatfishObjectMapper.mapper();
                Answer answer = reader.readValue(answerString, Answer.class);
                String newAnswerString = BatfishObjectMapper.writeString(answer);
                JsonNode tree = reader.readTree(answerString);
                JsonNode newTree = reader.readTree(newAnswerString);
                if (!CommonUtil.checkJsonEqual(tree, newTree)) {
                    // if (!tree.equals(newTree)) {
                    _logger.errorf("Original and recovered Json are different. Recovered = %s\n", newAnswerString);
                }
            } catch (Exception e) {
                _logger.outputf("Could NOT deserialize Json to Answer: %s\n", e.getMessage());
            }
        }
    }
    // get and print the log when in debugging mode
    if (_logger.getLogLevel() >= BatfishLogger.LEVEL_DEBUG) {
        _logger.output("---------------- Service Log --------------\n");
        String logFileName = wItem.getId() + BfConsts.SUFFIX_LOG_FILE;
        String downloadedFileStr = _workHelper.getObject(wItem.getContainerName(), wItem.getTestrigName(), logFileName);
        if (downloadedFileStr == null) {
            _logger.errorf("Failed to get log file %s\n", logFileName);
            return false;
        } else {
            Path downloadedFile = Paths.get(downloadedFileStr);
            CommonUtil.outputFileLines(downloadedFile, _logger::output);
        }
    }
    return true;
}
Also used : Path(java.nio.file.Path) Answer(org.batfish.datamodel.answers.Answer) BatfishException(org.batfish.common.BatfishException) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) BatfishObjectMapper(org.batfish.common.util.BatfishObjectMapper) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) EndOfFileException(org.jline.reader.EndOfFileException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) UserInterruptException(org.jline.reader.UserInterruptException) PatternSyntaxException(java.util.regex.PatternSyntaxException) FileNotFoundException(java.io.FileNotFoundException) BatfishException(org.batfish.common.BatfishException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 10 with BatfishException

use of org.batfish.common.BatfishException in project batfish by batfish.

the class Client method parseParams.

private Map<String, JsonNode> parseParams(String paramsLine) {
    String jsonParamsStr = "{ " + paramsLine + " }";
    Map<String, JsonNode> parameters;
    try {
        parameters = BatfishObjectMapper.mapper().readValue(new JSONObject(jsonParamsStr).toString(), new TypeReference<Map<String, JsonNode>>() {
        });
        return parameters;
    } catch (JSONException | IOException e) {
        throw new BatfishException("Failed to parse parameters. (Are all key-value pairs separated by commas? Are all " + "values valid JSON?)", e);
    }
}
Also used : BatfishException(org.batfish.common.BatfishException) JSONObject(org.codehaus.jettison.json.JSONObject) JSONException(org.codehaus.jettison.json.JSONException) JsonNode(com.fasterxml.jackson.databind.JsonNode) TypeReference(com.fasterxml.jackson.core.type.TypeReference) IOException(java.io.IOException)

Aggregations

BatfishException (org.batfish.common.BatfishException)264 IOException (java.io.IOException)61 Path (java.nio.file.Path)54 CleanBatfishException (org.batfish.common.CleanBatfishException)35 RedFlagBatfishException (org.batfish.common.RedFlagBatfishException)34 TreeMap (java.util.TreeMap)31 ArrayList (java.util.ArrayList)30 JSONException (org.codehaus.jettison.json.JSONException)30 Ip (org.batfish.datamodel.Ip)25 JSONObject (org.codehaus.jettison.json.JSONObject)25 Configuration (org.batfish.datamodel.Configuration)24 Map (java.util.Map)23 Prefix (org.batfish.datamodel.Prefix)22 HashMap (java.util.HashMap)20 HashSet (java.util.HashSet)20 TreeSet (java.util.TreeSet)20 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)18 Test (org.junit.Test)18 Set (java.util.Set)17 SortedMap (java.util.SortedMap)17