Search in sources :

Example 16 with MalformedInputException

use of java.nio.charset.MalformedInputException in project zaproxy by zaproxy.

the class ExtensionScript method postInit.

@Override
public void postInit() {
    ScriptEngineWrapper ecmaScriptEngineWrapper = null;
    final List<String[]> scriptsNotAdded = new ArrayList<>(1);
    for (ScriptWrapper script : this.getScriptParam().getScripts()) {
        // Change scripts using Rhino (Java 7) script engine to Nashorn (Java 8+).
        if (script.getEngine() == null && isRhinoScriptEngine(script.getEngineName())) {
            if (ecmaScriptEngineWrapper == null) {
                ecmaScriptEngineWrapper = getEcmaScriptEngineWrapper();
            }
            if (ecmaScriptEngineWrapper != null) {
                logger.info("Changing [" + script.getName() + "] (ECMAScript) script engine from [" + script.getEngineName() + "] to [" + ecmaScriptEngineWrapper.getEngineName() + "].");
                script.setEngine(ecmaScriptEngineWrapper);
            }
        }
        try {
            this.loadScript(script);
            if (script.getType() != null) {
                this.addScript(script, false, false);
            } else {
                logger.warn("Failed to add script \"" + script.getName() + "\", provided script type \"" + script.getTypeName() + "\" not found, available: " + getScriptTypesNames());
                scriptsNotAdded.add(new String[] { script.getName(), script.getEngineName(), Constant.messages.getString("script.info.scriptsNotAdded.error.missingType", script.getTypeName()) });
            }
        } catch (MalformedInputException e) {
            logger.warn("Failed to add script \"" + script.getName() + "\", contains invalid character sequence (UTF-8).");
            scriptsNotAdded.add(new String[] { script.getName(), script.getEngineName(), Constant.messages.getString("script.info.scriptsNotAdded.error.invalidChars") });
        } catch (InvalidParameterException | IOException e) {
            logger.error(e.getMessage(), e);
            scriptsNotAdded.add(new String[] { script.getName(), script.getEngineName(), Constant.messages.getString("script.info.scriptsNotAdded.error.other") });
        }
    }
    informScriptsNotAdded(scriptsNotAdded);
    this.loadTemplates();
    for (File dir : this.getScriptParam().getScriptDirs()) {
        // Load the scripts from subdirectories of each directory configured
        int numAdded = addScriptsFromDir(dir);
        logger.debug("Added " + numAdded + " scripts from dir: " + dir.getAbsolutePath());
    }
    shouldLoadScriptsOnScriptTypeRegistration = true;
    Path defaultScriptsDir = Paths.get(Constant.getZapHome(), SCRIPTS_DIR, SCRIPTS_DIR);
    for (ScriptType scriptType : typeMap.values()) {
        Path scriptTypeDir = defaultScriptsDir.resolve(scriptType.getName());
        if (Files.notExists(scriptTypeDir)) {
            try {
                Files.createDirectories(scriptTypeDir);
            } catch (IOException e) {
                logger.warn("Failed to create directory for script type: " + scriptType.getName(), e);
            }
        }
    }
}
Also used : Path(java.nio.file.Path) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) IOException(java.io.IOException) InvalidParameterException(java.security.InvalidParameterException) MalformedInputException(java.nio.charset.MalformedInputException) File(java.io.File)

Example 17 with MalformedInputException

use of java.nio.charset.MalformedInputException in project zaproxy by zaproxy.

the class ScriptAPI method handleApiAction.

@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
    if (ACTION_ENABLE.equals(name)) {
        ScriptWrapper script = extension.getScript(params.getString(ACTION_PARAM_SCRIPT_NAME));
        if (script == null) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST, ACTION_PARAM_SCRIPT_NAME);
        }
        if (!script.getType().isEnableable()) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, ACTION_PARAM_SCRIPT_NAME);
        }
        if (script.getEngine() == null) {
            throw new ApiException(ApiException.Type.BAD_STATE, "Unable to enable the script, script engine not available: " + script.getEngineName());
        }
        extension.setEnabled(script, true);
        return ApiResponseElement.OK;
    } else if (ACTION_DISABLE.equals(name)) {
        ScriptWrapper script = extension.getScript(params.getString(ACTION_PARAM_SCRIPT_NAME));
        if (script == null) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST, ACTION_PARAM_SCRIPT_NAME);
        }
        if (!script.getType().isEnableable()) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, ACTION_PARAM_SCRIPT_NAME);
        }
        extension.setEnabled(script, false);
        return ApiResponseElement.OK;
    } else if (ACTION_LOAD.equals(name)) {
        ScriptType type = extension.getScriptType(params.getString(ACTION_PARAM_SCRIPT_TYPE));
        if (type == null) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST, ACTION_PARAM_SCRIPT_TYPE);
        }
        ScriptEngineWrapper engine;
        try {
            engine = extension.getEngineWrapper(params.getString(ACTION_PARAM_SCRIPT_ENGINE));
        } catch (InvalidParameterException e) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST, ACTION_PARAM_SCRIPT_ENGINE, e);
        }
        File file = new File(params.getString(ACTION_PARAM_FILE_NAME));
        if (!file.exists()) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST, file.getAbsolutePath());
        }
        if (extension.getScript(params.getString(ACTION_PARAM_SCRIPT_NAME)) != null) {
            throw new ApiException(ApiException.Type.ALREADY_EXISTS, ACTION_PARAM_SCRIPT_NAME);
        }
        ScriptWrapper script = new ScriptWrapper(params.getString(ACTION_PARAM_SCRIPT_NAME), getParam(params, ACTION_PARAM_SCRIPT_DESC, ""), engine, type, true, file);
        Charset charset = getCharset(params);
        try {
            if (charset != null) {
                extension.loadScript(script, charset);
            } else {
                extension.loadScript(script);
            }
        } catch (MalformedInputException e) {
            throw new ApiException(charset != null ? ApiException.Type.ILLEGAL_PARAMETER : ApiException.Type.MISSING_PARAMETER, ACTION_PARAM_CHARSET, e);
        } catch (IOException e) {
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e);
        }
        extension.addScript(script, false);
        return ApiResponseElement.OK;
    } else if (ACTION_REMOVE.equals(name)) {
        ScriptWrapper script = extension.getScript(params.getString(ACTION_PARAM_SCRIPT_NAME));
        if (script == null) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST, ACTION_PARAM_SCRIPT_NAME);
        }
        extension.removeScript(script);
        return ApiResponseElement.OK;
    } else if (ACTION_RUN_STANDALONE.equals(name)) {
        ScriptWrapper script = extension.getScript(params.getString(ACTION_PARAM_SCRIPT_NAME));
        if (script == null) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST, ACTION_PARAM_SCRIPT_NAME);
        }
        if (!script.getType().getName().equals(ExtensionScript.TYPE_STANDALONE)) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, "Parameter " + ACTION_PARAM_SCRIPT_NAME + " does not match a " + ExtensionScript.TYPE_STANDALONE + " script.");
        }
        try {
            extension.invokeScript(script);
        } catch (Exception e) {
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e);
        }
        return ApiResponseElement.OK;
    } else if (ACTION_CLEAR_GLOBAL_VAR.equals(name)) {
        ScriptVars.setGlobalVar(params.getString(PARAM_VAR_KEY), null);
        return ApiResponseElement.OK;
    } else if (ACTION_CLEAR_GLOBAL_CUSTOM_VAR.equals(name)) {
        ScriptVars.setGlobalCustomVar(params.getString(PARAM_VAR_KEY), null);
        return ApiResponseElement.OK;
    } else if (ACTION_CLEAR_GLOBAL_VARS.equals(name)) {
        ScriptVars.clearGlobalVars();
        return ApiResponseElement.OK;
    } else if (ACTION_CLEAR_SCRIPT_VAR.equals(name)) {
        ScriptVars.setScriptVar(getAndValidateScriptName(params), params.getString(PARAM_VAR_KEY), null);
        return ApiResponseElement.OK;
    } else if (ACTION_CLEAR_SCRIPT_CUSTOM_VAR.equals(name)) {
        ScriptVars.setScriptCustomVar(getAndValidateScriptName(params), params.getString(PARAM_VAR_KEY), null);
        return ApiResponseElement.OK;
    } else if (ACTION_CLEAR_SCRIPT_VARS.equals(name)) {
        ScriptVars.clearScriptVars(getAndValidateScriptName(params));
        return ApiResponseElement.OK;
    } else if (ACTION_SET_GLOBAL_VAR.equals(name)) {
        ScriptVars.setGlobalVar(params.getString(PARAM_VAR_KEY), params.getString(PARAM_VAR_VALUE));
        return ApiResponseElement.OK;
    } else if (ACTION_SET_SCRIPT_VAR.equals(name)) {
        ScriptVars.setScriptVar(getAndValidateScriptName(params), params.getString(PARAM_VAR_KEY), params.getString(PARAM_VAR_VALUE));
        return ApiResponseElement.OK;
    } else {
        throw new ApiException(ApiException.Type.BAD_VIEW);
    }
}
Also used : InvalidParameterException(java.security.InvalidParameterException) MalformedInputException(java.nio.charset.MalformedInputException) Charset(java.nio.charset.Charset) IOException(java.io.IOException) File(java.io.File) MalformedInputException(java.nio.charset.MalformedInputException) ApiException(org.zaproxy.zap.extension.api.ApiException) IOException(java.io.IOException) InvalidParameterException(java.security.InvalidParameterException) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 18 with MalformedInputException

use of java.nio.charset.MalformedInputException in project AntennaPod by AntennaPod.

the class ID3Reader method readEncodedString2.

/**
 * Reads chars where the encoding uses 2 chars per symbol.
 */
private String readEncodedString2(Charset charset, int max) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    int bytesRead = 0;
    boolean foundEnd = false;
    while (bytesRead + 1 < max) {
        byte c1 = readByte();
        byte c2 = readByte();
        if (c1 == 0 && c2 == 0) {
            foundEnd = true;
            break;
        }
        bytesRead += 2;
        bytes.write(c1);
        bytes.write(c2);
    }
    if (!foundEnd && bytesRead < max) {
        // Last character
        byte c = readByte();
        if (c != 0) {
            bytes.write(c);
        }
    }
    try {
        return charset.newDecoder().decode(ByteBuffer.wrap(bytes.toByteArray())).toString();
    } catch (MalformedInputException e) {
        return "";
    }
}
Also used : MalformedInputException(java.nio.charset.MalformedInputException) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 19 with MalformedInputException

use of java.nio.charset.MalformedInputException in project jgnash by ccavanaugh.

the class FileMagic method isOfxV2.

public static boolean isOfxV2(final Path path) {
    boolean result = false;
    if (Files.exists(path)) {
        try (final BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            String line = reader.readLine();
            /* Assume that the OFX file is one continuous string of information when searching for OFXHEADER */
            while (line != null) {
                line = line.trim();
                // consume any processing instructions and check for ofx 2.0 hints
                if (!line.isEmpty() && line.startsWith("<?")) {
                    if (line.contains("OFXHEADER=\"200\"")) {
                        result = true;
                        break;
                    }
                } else if (!line.isEmpty()) {
                    // allow empty lines at the beginning of the file
                    if (line.startsWith("<OFX>")) {
                        // must be ofx
                        result = true;
                    }
                    break;
                }
                line = reader.readLine();
            }
        } catch (final MalformedInputException mie) {
            // caused by binary file
            result = false;
            Logger.getLogger(FileMagic.class.getName()).info("Tried to read a binary file");
        } catch (IOException e) {
            Logger.getLogger(FileMagic.class.getName()).log(Level.SEVERE, e.toString(), e);
        }
    }
    return result;
}
Also used : BufferedReader(java.io.BufferedReader) MalformedInputException(java.nio.charset.MalformedInputException) IOException(java.io.IOException)

Example 20 with MalformedInputException

use of java.nio.charset.MalformedInputException in project jgnash by ccavanaugh.

the class FileMagic method getOfxV1Encoding.

/**
 * Determine the correct character encoding of an OFX Version 1 file.
 *
 * @param path File to look at
 * @return encoding of the file
 */
private static String getOfxV1Encoding(final Path path, final Charset charset) throws MalformedInputException {
    String encoding = null;
    String characterSet = null;
    if (Files.exists(path)) {
        try (final BufferedReader reader = Files.newBufferedReader(path, charset)) {
            String line = reader.readLine();
            while (line != null) {
                line = line.trim();
                if (!line.isEmpty()) {
                    // allow empty lines at the beginning of the file
                    if (line.startsWith("ENCODING:")) {
                        String[] splits = COLON_DELIMITER_PATTERN.split(line);
                        if (splits.length == 2) {
                            encoding = splits[1];
                        }
                    } else if (line.startsWith("CHARSET:")) {
                        String[] splits = COLON_DELIMITER_PATTERN.split(line);
                        if (splits.length == 2) {
                            characterSet = splits[1];
                        }
                    }
                    if (encoding != null && characterSet != null) {
                        break;
                    }
                }
                line = reader.readLine();
            }
        } catch (final MalformedInputException e) {
            // rethrow
            throw e;
        } catch (final IOException e) {
            LogUtil.logSevere(FileMagic.class, e);
        }
    }
    if (encoding != null && characterSet != null) {
        if (encoding.equals(StandardCharsets.UTF_8.name()) && characterSet.equals("CSUNICODE")) {
            return ISO_8859_1.name();
        } else if (encoding.equals(StandardCharsets.UTF_8.name())) {
            return StandardCharsets.UTF_8.name();
        } else if (encoding.equals(USASCII) && characterSet.equals("1252")) {
            return WINDOWS_1252;
        } else if (encoding.equals(USASCII) && characterSet.contains("8859-1")) {
            return "ISO-8859-1";
        } else if (encoding.equals(USASCII) && characterSet.equals("NONE")) {
            return WINDOWS_1252;
        }
    }
    return WINDOWS_1252;
}
Also used : BufferedReader(java.io.BufferedReader) MalformedInputException(java.nio.charset.MalformedInputException) IOException(java.io.IOException)

Aggregations

MalformedInputException (java.nio.charset.MalformedInputException)41 IOException (java.io.IOException)14 ByteBuffer (java.nio.ByteBuffer)12 CharBuffer (java.nio.CharBuffer)9 UnmappableCharacterException (java.nio.charset.UnmappableCharacterException)9 CharsetDecoder (java.nio.charset.CharsetDecoder)7 BufferedReader (java.io.BufferedReader)6 Path (java.nio.file.Path)6 File (java.io.File)5 InputStreamReader (java.io.InputStreamReader)5 Charset (java.nio.charset.Charset)5 Test (org.junit.Test)4 CharacterCodingException (java.nio.charset.CharacterCodingException)3 MalformedInputExceptionWithDetail (org.eclipse.wst.sse.core.internal.exceptions.MalformedInputExceptionWithDetail)3 JSONException (com.alibaba.fastjson.JSONException)2 BufferedWriter (java.io.BufferedWriter)2 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 UncheckedIOException (java.io.UncheckedIOException)2 StandardCharsets (java.nio.charset.StandardCharsets)2