Example usage for java.util.regex PatternSyntaxException getMessage

List of usage examples for java.util.regex PatternSyntaxException getMessage

Introduction

In this page you can find the example usage for java.util.regex PatternSyntaxException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular-expression pattern, and a visual indication of the error index within the pattern.

Usage

From source file:org.jahia.utils.properties.PropertiesManager.java

/**
* Store new properties and values in the properties file.
* If the file where you want to write doesn't exists, the file is created.
* @author  Alexandre Kraft/*from w w w.j a  va 2 s  .c o m*/
* @author  Khue N'Guyen
*
* @param   propertiesFilePath  The filesystem path where the file is saved.
*/
public void storeProperties(String propertiesFilePath) throws NullPointerException {
    File propertiesFileObject = new File(propertiesFilePath);
    File propertiesFileFolder = propertiesFileObject.getParentFile();

    // check if the destination folder exists and create it if needed...
    if (!propertiesFileFolder.exists()) {
        propertiesFileFolder.mkdirs();
        propertiesFileFolder = null;
    }

    try {
        if (new File(this.propertiesFilePath).exists()) {
            List bufferList = new ArrayList();
            String lineReaded = null;

            BufferedReader buffered = new BufferedReader(new FileReader(this.propertiesFilePath));
            int position = 0;

            // compose all properties List, used to find the new properties...
            List allProperties = new ArrayList();
            Iterator allPropertiesEnumeration = new EnumerationIterator(properties.propertyNames());
            while (allPropertiesEnumeration.hasNext()) {
                allProperties.add((String) allPropertiesEnumeration.next());
            }

            // parse the file...
            while ((lineReaded = buffered.readLine()) != null) {
                try {
                    lineReaded = lineReaded.replaceAll("\\t", "    "); //now supports Tab characters in lines
                    if (!lineReaded.trim().equals("") && !lineReaded.trim().substring(0, 1).equals("#")) {
                        boolean propertyFound = false;
                        Iterator propertyNames = allProperties.iterator();

                        while (propertyNames.hasNext() && !propertyFound) {
                            String propertyName = (String) propertyNames.next();
                            String propvalue = properties.getProperty(propertyName);

                            if (lineReaded.indexOf(propertyName + " ") == 0) {
                                position = lineReaded.indexOf("=");
                                if (position >= 0) {
                                    propertyFound = true;

                                    StringBuilder thisLineBuffer = new StringBuilder();
                                    thisLineBuffer.append(lineReaded.substring(0, position + 1));
                                    thisLineBuffer.append("   ");
                                    thisLineBuffer.append(string2Property(propvalue));
                                    bufferList.add(thisLineBuffer.toString());

                                    // remove this line from allProperties to affine the search and to find new properties...
                                    allProperties.remove(propertyName);
                                }
                            }
                        }
                    } else {
                        // this is a special line only for layout, like a comment or a blank line...
                        bufferList.add(lineReaded.trim());
                    }
                } catch (IndexOutOfBoundsException ioobe) {
                } catch (PatternSyntaxException ex1) {
                    logger.error(ex1.getMessage(), ex1);
                } catch (IllegalArgumentException ex2) {
                    logger.error(ex2.getMessage(), ex2);
                }
            }

            // add not found properties at the end of the file (and the jahia.properties layout is keeping)...
            Iterator restantPropertyNames = allProperties.iterator();
            while (restantPropertyNames.hasNext()) {
                String restantPropertyName = (String) restantPropertyNames.next();
                StringBuilder specialLineBuffer = new StringBuilder();
                specialLineBuffer.append(restantPropertyName);
                for (int i = 0; i < 55 - restantPropertyName.length(); i++) {
                    specialLineBuffer.append(" ");
                }
                specialLineBuffer.append("=   ");
                specialLineBuffer.append(properties.getProperty(restantPropertyName));
                bufferList.add(specialLineBuffer.toString());
            }

            // close the buffered filereader...
            buffered.close();

            // write the file...
            writeTheFile(propertiesFilePath, bufferList);
        } else {
            FileOutputStream outputStream = new FileOutputStream(propertiesFileObject);
            try {
                properties.store(outputStream, "This file has been written by Jahia.");
            } finally {
                outputStream.close();
            }
        }
    } catch (java.io.IOException ioe) {
    }
}

From source file:org.jetbrains.generate.tostring.config.FilterPattern.java

public Pattern getFieldNamePattern() {
    if (StringUtil.isEmpty(fieldName)) {
        return null;
    }//from   w  ww  . ja va2s .c  o m
    if (fieldNamePattern == null) {
        try {
            fieldNamePattern = Pattern.compile(fieldName);
        } catch (PatternSyntaxException e) {
            fieldName = null;
            LOG.warn(e.getMessage());
        }
    }
    return fieldNamePattern;
}

From source file:org.jetbrains.generate.tostring.config.FilterPattern.java

public Pattern getMethodNamePattern() {
    if (StringUtil.isEmpty(methodName)) {
        return null;
    }/*  w  w w . j a  va 2  s .  c  o m*/
    if (methodNamePattern == null) {
        try {
            methodNamePattern = Pattern.compile(methodName);
        } catch (PatternSyntaxException e) {
            methodName = null;
            LOG.warn(e.getMessage());
        }
    }
    return methodNamePattern;
}

From source file:org.jetbrains.generate.tostring.config.FilterPattern.java

public Pattern getFieldTypePattern() {
    if (StringUtil.isEmpty(fieldType)) {
        return null;
    }//from   www.  j a v  a 2 s .  com
    if (fieldTypePattern == null) {
        try {
            fieldTypePattern = Pattern.compile(fieldType);
        } catch (PatternSyntaxException e) {
            fieldType = null;
            LOG.warn(e.getMessage());
        }
    }
    return fieldTypePattern;
}

From source file:org.jetbrains.generate.tostring.config.FilterPattern.java

public Pattern getMethodTypePattern() {
    if (StringUtil.isEmpty(methodType)) {
        return null;
    }// w  w w .ja v  a2 s .c o  m
    if (methodTypePattern == null) {
        try {
            methodTypePattern = Pattern.compile(methodType);
        } catch (PatternSyntaxException e) {
            methodType = null;
            LOG.warn(e.getMessage());
        }
    }
    return methodTypePattern;
}

From source file:org.sakaiproject.util.RemoteHostFilter.java

/**
 * Converts the given list of comma-delimited regex patterns to an array of
 * Pattern objects//www. j av a2 s  . c  o m
 * 
 * @param list
 *            The comma-separated list of patterns
 * 
 * @exception IllegalArgumentException
 *                if one of the patterns has invalid regular expression
 *                syntax
 */
protected Pattern[] getRegExPatterns(String list) {

    if (list == null)
        return EMPTY_PATTERN;

    list = list.trim();
    if (list.length() < 1)
        return EMPTY_PATTERN;

    StringTokenizer st = new StringTokenizer(list, ",");

    ArrayList<Pattern> patterns = new ArrayList<Pattern>();
    while (st.hasMoreTokens()) {
        String token = st.nextToken().trim();
        try {
            // Host names are case insensitive
            patterns.add(Pattern.compile(token, Pattern.CASE_INSENSITIVE));
        } catch (PatternSyntaxException e) {
            throw new IllegalArgumentException(
                    "Illegal Regular Expression Syntax: [" + token + "] - " + e.getMessage());
        }
    }
    return ((Pattern[]) patterns.toArray(EMPTY_PATTERN));
}

From source file:org.talend.dataprep.transformation.actions.text.ExtractStringTokens.java

@Override
public void compile(ActionContext context) {
    super.compile(context);
    if (context.getActionStatus() == ActionContext.ActionStatus.OK) {

        final String regex = context.getParameters().get(PARAMETER_REGEX);

        // Validate the regex, and put it in context once for all lines:
        // Check 1: not null or empty
        if (StringUtils.isEmpty(regex)) {
            LOGGER.debug("Empty pattern, action canceled");
            context.setActionStatus(ActionContext.ActionStatus.CANCELED);
            return;
        }//from w  w  w . j  a  va2 s .com
        // Check 2: valid regex
        try {
            context.get(PATTERN, p -> Pattern.compile(regex));
        } catch (PatternSyntaxException e) {
            LOGGER.debug("Invalid pattern {} --> {}, action canceled", regex, e.getMessage(), e);
            context.setActionStatus(ActionContext.ActionStatus.CANCELED);
        }
        // Create result column
        final Map<String, String> parameters = context.getParameters();
        final String columnId = context.getColumnId();

        // create the new columns
        int limit = parameters.get(MODE_PARAMETER).equals(MULTIPLE_COLUMNS_MODE)
                ? Integer.parseInt(parameters.get(LIMIT))
                : 1;

        final RowMetadata rowMetadata = context.getRowMetadata();
        final ColumnMetadata column = rowMetadata.getById(columnId);
        final List<String> newColumns = new ArrayList<>();
        final Deque<String> lastColumnId = new ArrayDeque<>();
        lastColumnId.push(columnId);
        for (int i = 0; i < limit; i++) {
            final int newColumnIndex = i + 1;
            newColumns.add(context.column(column.getName() + APPENDIX + i, r -> {
                final ColumnMetadata c = ColumnMetadata.Builder //
                        .column() //
                        .type(Type.STRING) //
                        .computedId(StringUtils.EMPTY) //
                        .name(column.getName() + APPENDIX + newColumnIndex) //
                        .build();
                lastColumnId.push(rowMetadata.insertAfter(lastColumnId.pop(), c));
                return c;
            }));
        }

    }
}

From source file:pl.otros.vfs.browser.table.VfsTableModelFileNameRowFilter.java

boolean checkIfInclude(String baseName, String patternText) {
    Pattern pattern = null;//from www. j  a  v a2  s.c  om
    try {
        String patternString = preparePatternString(patternText);
        pattern = Pattern.compile(patternString);
    } catch (PatternSyntaxException pse) {
        LOGGER.error(pse.getMessage());
        //if pattern can't be compiled we will use String contains test
    }
    LOGGER.debug(String.format("pattern=(%s)", pattern));
    return StringUtils.containsIgnoreCase(baseName, patternText) || (pattern == null) ? true
            : pattern.matcher(baseName).matches();
}

From source file:pl.umk.mat.zawodyweb.compiler.classes.LanguageMAIN.java

/**
 * Sprawdza rozwizanie na input/*from  w w w . j  a v  a 2s  .c o  m*/
 * @param path kod rdowy
 * @param input w formacie:
 *              <pre>c=NUMER_KONKURSU<br/>t=NUMER_ZADANIA<br/>m=MAX_POINTS</pre>
 * @return
 */
@Override
public TestOutput runTest(String path, TestInput input) {
    TestOutput result = new TestOutput(null);

    Integer contest_id = null;
    Integer task_id = null;
    Integer max_points = null;
    try {
        try {
            Matcher matcher = null;

            matcher = Pattern.compile("c=([0-9]+)").matcher(input.getInputText());
            if (matcher.find()) {
                contest_id = Integer.valueOf(matcher.group(1));
            }

            matcher = Pattern.compile("t=([0-9]+)").matcher(input.getInputText());
            if (matcher.find()) {
                task_id = Integer.valueOf(matcher.group(1));
            }

            matcher = Pattern.compile("m=([0-9]+)").matcher(input.getInputText());
            if (matcher.find()) {
                max_points = Integer.valueOf(matcher.group(1));
            }

            if (contest_id == null) {
                throw new IllegalArgumentException("task_id == null");
            }
            if (task_id == null) {
                throw new IllegalArgumentException("task_id == null");
            }
        } catch (PatternSyntaxException ex) {
            throw new IllegalArgumentException(ex);
        } catch (NumberFormatException ex) {
            throw new IllegalArgumentException(ex);
        } catch (IllegalStateException ex) {
            throw new IllegalArgumentException(ex);
        }
    } catch (IllegalArgumentException e) {
        logger.error("Exception when parsing input", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("MAIN IllegalArgumentException");
        return result;
    }
    logger.debug("Contest id = " + contest_id);
    logger.debug("Task id = " + task_id);
    logger.debug("Max points = " + max_points);

    String loginUrl = "http://main.edu.pl/pl/login";
    String login = properties.getProperty("main_edu_pl.login");
    String password = properties.getProperty("main_edu_pl.password");

    HttpClient client = new HttpClient();

    HttpClientParams params = client.getParams();
    params.setParameter("http.useragent", "Opera/9.64 (Windows NT 6.0; U; pl) Presto/2.1.1");
    //params.setParameter("http.protocol.handle-redirects", true);
    client.setParams(params);
    /* logowanie */
    logger.debug("Logging in");
    PostMethod postMethod = new PostMethod(loginUrl);
    NameValuePair[] dataLogging = { new NameValuePair("auth", "1"), new NameValuePair("login", login),
            new NameValuePair("pass", password) };
    postMethod.setRequestBody(dataLogging);
    try {
        client.executeMethod(postMethod);
        if (Pattern.compile("Logowanie udane").matcher(postMethod.getResponseBodyAsString(1024 * 1024))
                .find() == false) {
            logger.error("Unable to login (" + login + ":" + password + ")");
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setOutputText("Logging in failed");
            postMethod.releaseConnection();
            return result;
        }
    } catch (HttpException e) {
        logger.error("Exception when logging in", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("HttpException");
        postMethod.releaseConnection();
        return result;
    } catch (IOException e) {
        logger.error("Exception when logging in", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("IOException");
        postMethod.releaseConnection();
        return result;
    }
    postMethod.releaseConnection();

    /* wchodzenie na stron z wysyaniem zada i pobieranie pl z hidden */
    logger.debug("Getting submit page");
    ArrayList<Part> values = new ArrayList<Part>();
    try {
        GetMethod getMethod = new GetMethod("http://main.edu.pl/user.phtml?op=submit&m=insert&c=" + contest_id);
        client.executeMethod(getMethod);
        String response = getMethod.getResponseBodyAsString(1024 * 1024);
        getMethod.releaseConnection();

        Matcher tagMatcher = Pattern.compile("<input[^>]*>").matcher(response);
        Pattern namePattern = Pattern.compile("name\\s*=\"([^\"]*)\"");
        Pattern valuePattern = Pattern.compile("value\\s*=\"([^\"]*)\"");
        while (tagMatcher.find()) {
            Matcher matcher = null;
            String name = null;
            String value = null;

            String inputTag = tagMatcher.group();

            matcher = namePattern.matcher(inputTag);
            if (matcher.find()) {
                name = matcher.group(1);
            }

            matcher = valuePattern.matcher(inputTag);
            if (matcher.find()) {
                value = matcher.group(1);
            }

            if (name != null && value != null && name.equals("solution") == false) {
                values.add(new StringPart(name, value));
            }
        }
    } catch (HttpException ex) {
        logger.error("Exception when getting submit page", ex);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(ex.getMessage());
        result.setOutputText("IOException");
        return result;
    } catch (IOException ex) {
        logger.error("Exception when getting submit page", ex);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(ex.getMessage());
        result.setOutputText("IOException");
        return result;
    }

    values.add(new StringPart("task", task_id.toString()));

    String filename = properties.getProperty("CODE_FILENAME");
    filename = filename.replaceAll("\\." + properties.getProperty("CODEFILE_EXTENSION") + "$", "");
    filename = filename + "." + properties.getProperty("CODEFILE_EXTENSION");
    FilePart filePart = new FilePart("solution", new ByteArrayPartSource(filename, path.getBytes()));
    values.add(filePart);

    /* wysyanie rozwizania */
    logger.debug("Submiting solution");
    Integer solution_id = null;
    postMethod = new PostMethod("http://main.edu.pl/user.phtml?op=submit&m=db_insert&c=" + contest_id);
    postMethod.setRequestEntity(new MultipartRequestEntity(values.toArray(new Part[0]), client.getParams()));
    try {
        try {
            client.executeMethod(postMethod);
            HttpMethod method = postMethod;

            /* check if redirect */
            Header locationHeader = postMethod.getResponseHeader("location");
            if (locationHeader != null) {
                String redirectLocation = locationHeader.getValue();
                GetMethod getMethod = new GetMethod(
                        new URI(postMethod.getURI(), new URI(redirectLocation, false)).getURI());
                client.executeMethod(getMethod);
                method = getMethod;
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            Matcher matcher = Pattern.compile("<tr id=\"rptr\">.*?</tr>", Pattern.DOTALL)
                    .matcher(sb.toString());
            if (matcher.find()) {
                Matcher idMatcher = Pattern.compile("id=([0-9]+)").matcher(matcher.group());
                if (idMatcher.find()) {
                    solution_id = Integer.parseInt(idMatcher.group(1));
                }
            }
            if (solution_id == null) {
                throw new IllegalArgumentException("solution_id == null");
            }
        } catch (HttpException e) {
            new IllegalArgumentException(e);
        } catch (IOException e) {
            new IllegalArgumentException(e);
        } catch (NumberFormatException e) {
            new IllegalArgumentException(e);
        } catch (IllegalStateException e) {
            new IllegalArgumentException(e);
        }

    } catch (IllegalArgumentException e) {
        logger.error("Exception when submiting solution", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("IllegalArgumentException");
        postMethod.releaseConnection();
        return result;
    }

    postMethod.releaseConnection();

    /* sprawdzanie statusu */
    logger.debug("Checking result for main.id=" + solution_id);
    Pattern resultRowPattern = Pattern.compile("id=" + solution_id + ".*?</tr>", Pattern.DOTALL);
    Pattern resultPattern = Pattern.compile(
            "</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?)</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?)</td>",
            Pattern.DOTALL);
    result_loop: while (true) {
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(e.getMessage());
            result.setOutputText("InterruptedException");
            return result;
        }

        GetMethod getMethod = new GetMethod("http://main.edu.pl/user.phtml?op=zgloszenia&c=" + contest_id);
        try {
            client.executeMethod(getMethod);
            String response = getMethod.getResponseBodyAsString(1024 * 1024);
            getMethod.releaseConnection();

            Matcher matcher = resultRowPattern.matcher(response);
            // "</td>.*?<td.*?>.*?[NAZWA_ZADANIA]</td>.*?<td.*?>(.*?[STATUS])</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?[PUNKTY])</td>"
            while (matcher.find()) {
                Matcher resultMatcher = resultPattern.matcher(matcher.group());

                if (resultMatcher.find() && resultMatcher.groupCount() == 2) {
                    String resultType = resultMatcher.group(1);
                    if (resultType.equals("?")) {
                        continue;
                    } else if (resultType.matches("B..d kompilacji")) { // CE
                        result.setStatus(ResultsStatusEnum.CE.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.matches("Program wyw.aszczony")) { // TLE
                        result.setStatus(ResultsStatusEnum.TLE.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.matches("B..d wykonania")) { // RTE
                        result.setStatus(ResultsStatusEnum.RE.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.matches("Z.a odpowied.")) { // WA
                        result.setStatus(ResultsStatusEnum.WA.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.equals("OK")) { // AC
                        result.setStatus(ResultsStatusEnum.ACC.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else {
                        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
                        result.setNotes("Unknown status: \"" + resultType + "\"");
                    }
                    break result_loop;
                }
            }
        } catch (HttpException ex) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(ex.getMessage());
            result.setOutputText("HttpException");
            return result;
        } catch (IOException ex) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(ex.getMessage());
            result.setOutputText("IOException");
            return result;
        }
    }
    return result;
}

From source file:rsg.RSG.java

/**
 * @param args the command line arguments
 *//*from   w w w  .  j a  va 2s .c  o m*/
public static void main(String[] args) throws IOException {
    // Define all commands
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption(OptionBuilder.withDescription("regex to generate the strings").hasArg()
            .withArgName("regex").create("r"));
    options.addOption(
            OptionBuilder.withDescription("num of Strings to print").hasArg().withArgName("size").create("s"));
    options.addOption(
            OptionBuilder.withDescription("print this message").hasArg(false).withLongOpt("help").create("h"));

    try {
        // Parse all command from arguments    
        CommandLine line = parser.parse(options, args);

        //check for neccessary parameter value
        if (args.length == 0) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("RSG", options);
            System.exit(0);
        }
        if (!line.hasOption("r")) {
            System.out.println("Please specifiy a regular expression with -r, see help(-h) for more details");
            System.exit(0);
        }
        if (line.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("RSG", options);
            System.exit(0);
        }
        if (!line.hasOption("s")) {
            System.out.println(
                    "Please enter the num of strings to print/write with the -s or --size parameter, see help(-h) for more details");
            System.exit(0);
        }

        String regex = line.getOptionValue("r");
        String fileName = line.getOptionValue("w");
        int size = Integer.parseInt(line.getOptionValue("s"));

        //check if the regex is valid
        boolean flag = false;
        try {
            Pattern.compile(regex);
            flag = true;
        } catch (PatternSyntaxException e) {
            System.out.println("The syntax of the regex you enter is incorrect:\n" + e.getMessage());
            System.exit(0);
        }

        //Generate the string 
        String output = "";
        for (int i = 0; i < size; i++) {
            Xeger generator = new Xeger(regex);
            String result = generator.generate();
            assert result.matches(regex);
            output += result + "\n";
        }

        //Print or Write to file
        System.out.println(output);

    }
    //catch exceptions
    catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
    } catch (NumberFormatException exp) {
        System.out.println("Error: " + exp.getMessage() + "\nThe size argument is not an interger\n");
    }

}