Example usage for java.util.regex Pattern DOTALL

List of usage examples for java.util.regex Pattern DOTALL

Introduction

In this page you can find the example usage for java.util.regex Pattern DOTALL.

Prototype

int DOTALL

To view the source code for java.util.regex Pattern DOTALL.

Click Source Link

Document

Enables dotall mode.

Usage

From source file:matteroverdrive.gui.pages.PageGuideDescription.java

private Map<String, String> loadStyleSheetMap(Element element) {
    if (element.hasAttribute("stylesheet")) {
        try {/* www . j a va2s . c  om*/
            Map<String, String> styleMap = new HashMap<>();
            InputStream stylesheetStream = Minecraft.getMinecraft().getResourceManager()
                    .getResource(new ResourceLocation(element.getAttribute("stylesheet"))).getInputStream();
            String rawStyle = IOUtils.toString(stylesheetStream, "UTF-8");
            rawStyle = rawStyle.replaceAll("\\r|\\n|\\s+", "");
            rawStyle = rawStyle.replaceAll("(?s)/\\*.*?\\*/", ""); //remove comments
            Matcher matcher = Pattern.compile("([^\\}\\{]+)(\\{[^\\}]+\\})", Pattern.DOTALL | Pattern.MULTILINE)
                    .matcher(rawStyle);
            while (matcher.find()) {
                styleMap.put(matcher.group(1), matcher.group(2).substring(1, matcher.group(2).length() - 1));
            }
            return styleMap;
        } catch (IOException e) {
            MatterOverdrive.log.log(Level.ERROR, e, "There was a problem loading the stylesheet");
        }
    }
    return null;
}

From source file:org.webguitoolkit.ui.controls.table.DefaultTableModel.java

/**
 * pattern for insensitive search/*from   w w  w .j a  va2  s  . c om*/
 */
protected Pattern compilePattern(String pattern) {

    if (!pattern.startsWith(ISREGULAREXPRESSION)) {
        pattern = escapeRegexLiterals(pattern);
        pattern = pattern.replaceAll("\\*", ".*");
        pattern = pattern.replaceAll("\\?", ".");
        if (!pattern.endsWith("*"))
            pattern += ".*";

    } else {
        pattern = regularExpressionFilter(pattern);
    }
    return Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL);
}

From source file:com.androzic.plugin.tracker.SMSReceiver.java

private boolean parseTK102Clone1(String text, Tracker tracker) {
    /* Clone TK-102/*from   w ww .j  a  v  a2 s.c o  m*/
             
    help me!
    lat:50.123456 long:39.123456
    speed:0.00
    T:13/09/30 10:27
    bat:100%
    http://maps.google.com/maps?f=q&q=50.... 
            
    lat:50.123456lon:39.123456
    speed:0.00
    T:13/09/30 10:27
    bat:100% 3597100123456789
    http://maps.google.com/maps?f=q&q=50.... 
            
    lat:51.123456lon:39.123456 speed:0.00 T:13/09/30 10:27 bat:100% 3597100123456789 http://maps.google.com
            
    */

    Log.w(TAG, "parseTK102Clone1");

    Pattern pattern = Pattern.compile(
            "(.*)?\\s?lat:\\s?([^\\sl]+)\\s?long?:\\s?([^\\s]+)\\s?speed:\\s?([\\d\\.]+)\\s?T:?([\\d/:\\.\\s]+)\\s?bat:([^%]+)%\\s?(\\d+)?(.+)",
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = pattern.matcher(text);
    if (!m.matches())
        return false;

    String latitude = m.group(2);
    String longitude = m.group(3);

    double coords[] = CoordinateParser.parse(latitude + " " + longitude);
    if (Double.isNaN(coords[0]) || Double.isNaN(coords[1]))
        return false;

    tracker.latitude = coords[0];
    tracker.longitude = coords[1];

    try {
        tracker.speed = Double.parseDouble(m.group(4)) / 3.6;
    } catch (NumberFormatException ignore) {
    }

    String time = m.group(5);
    try {
        Date date = TK102Clone1DateFormatter.parse(time);
        tracker.time = date.getTime();
    } catch (Exception e) {
        Log.e(TAG, "Date error", e);
    }

    String battery = m.group(6);
    try {
        tracker.battery = Integer.parseInt(battery);
    } catch (NumberFormatException ignore) {
    }

    String s_imei = m.group(7);

    if (s_imei != null)
        tracker.imei = s_imei;

    String message = m.group(1);
    if (!"".equals(message))
        tracker.message = message;

    return true;
}

From source file:de.mpg.mpdl.inge.syndication.feed.Feed.java

/**
 * Generate <code>UriMatcher</code> for the feed and list of the parameters <code>paramList</code>
 * according to the <code>uri</code>.
 * //from w  ww.  jav a  2s . co m
 * @param uri
 */
public void generateUriMatcher(final String uri) {
    String result = new String(uri);

    result = escapeUri(result);

    // property regexp in uri
    String regexp = "(\\$\\{[\\w.]+?\\})";

    Matcher m = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(uri);
    while (m.find()) {
        String param = m.group(1);
        paramList.add(param);
        result = result.replaceFirst(Utils.quoteReplacement(param), "\\(.+\\)?");
    }
    setUriMatcher(result);
}

From source file:org.etudes.util.HtmlHelper.java

/**
 * Remove any text that match the "comments from Word style definitions encoded into html by Tiny" from the data.
 * /*w w  w.  j a  v a2s . co  m*/
 * @param data
 *        the html data.
 * @return The cleaned up data.
 */
public static String stripEncodedStyleDefinitionComments(String data) {
    if (data == null)
        return data;

    // quick check for any hint of the pattern
    if (data.indexOf("&lt;!-- /* Style Definitions */") == -1)
        return data;

    // Notes: DOTALL so the "." matches line terminators too, "*?" Reluctant quantifier so text between two different comments is not lost
    Pattern p = Pattern.compile("&lt;!-- /\\* Style Definitions \\*/.*?--&gt;",
            Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL);

    Matcher m = p.matcher(data);
    StringBuffer sb = new StringBuffer();

    while (m.find()) {
        m.appendReplacement(sb, "");
    }

    m.appendTail(sb);

    return sb.toString();
}

From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.LoadClinicalDataListener.java

@Override
public void handleEvent(Event event) {
    loadDataUI.openLoadingShell();// w  w w .  j  a  va  2s  .  co m
    new Thread() {
        public void run() {
            String jobPath;
            try {
                String[] splited = loadDataUI.getTopNode().split("\\\\", -1);
                if (splited[0].compareTo("") != 0) {
                    loadDataUI.setMessage("A study node has to begin by the character '\\'");
                    loadDataUI.setIsLoading(false);
                    return;
                }
                try {
                    Class.forName("oracle.jdbc.driver.OracleDriver");
                    String connectionString = "jdbc:oracle:thin:@" + PreferencesHandler.getDbServer() + ":"
                            + PreferencesHandler.getDbPort() + ":" + PreferencesHandler.getDbName();

                    Connection con = DriverManager.getConnection(connectionString,
                            PreferencesHandler.getMetadataUser(), PreferencesHandler.getMetadataPwd());
                    Statement stmt = con.createStatement();
                    ResultSet rs = stmt
                            .executeQuery("select * from table_access where c_name='" + splited[1] + "'");
                    if (!rs.next()) {//have to add a top node
                        stmt.executeQuery("insert into table_access(" + "c_table_cd," + "c_table_name,"
                                + "c_protected_access," + "c_hlevel," + "c_fullname," + "c_name,"
                                + "c_synonym_cd," + "c_visualattributes," + "c_totalnum," + "c_facttablecolumn,"
                                + "c_dimtablename," + "c_columnname," + "c_columndatatype," + "c_operator,"
                                + "c_dimcode," + "c_tooltip," + "c_status_cd) values(" + "'" + splited[1] + "',"
                                + "'i2b2'," + "'N'," + "0," + "'\\" + splited[1] + "\\'," + "'" + splited[1]
                                + "'," + "'N'," + "'CA'," + "0," + "'concept_cd'," + "'concept_dimension',"
                                + "'concept_path'," + "'T'," + "'LIKE'," + "'\\" + splited[1] + "\\'," + "'\\"
                                + splited[1] + "\\'," + "'A')");
                        stmt.executeQuery("insert into i2b2 values(0, '\\" + splited[1] + "\\', '" + splited[1]
                                + "','N','CA',0,null, null, 'CONCEPT_CD','CONCEPT_DIMENSION','CONCEPT_PATH', 'T', 'LIKE','\\"
                                + splited[1] + "\\', null, '\\" + splited[1]
                                + "\\', sysdate, null, null, null, null, null, '@', null, null, null)");
                    }

                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    loadDataUI.setMessage("SQL exception: " + e.getLocalizedMessage());
                    loadDataUI.setIsLoading(false);
                    return;
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    loadDataUI.setMessage("Class Not Found exception");
                    loadDataUI.setIsLoading(false);
                    return;
                }

                //initiate kettle environment
                GlobalMessages.setLocale(EnvUtil.createLocale("en-US"));
                KettleEnvironment.init(false);

                //find the kettle job to initiate the loading
                URL jobUrl = new URL(
                        "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/create_clinical_data.kjb");
                jobUrl = FileLocator.toFileURL(jobUrl);
                jobPath = jobUrl.getPath();
                //create a new job from the kettle file

                JobMeta jobMeta = new JobMeta(jobPath, null);
                Job job = new Job(null, jobMeta);

                //find the other files needed for job and put them in the cache
                jobUrl = new URL(
                        "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/validate_clinical_data_params.ktr");
                jobUrl = FileLocator.toFileURL(jobUrl);
                jobUrl = new URL("platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/get_data_filenames.ktr");
                jobUrl = FileLocator.toFileURL(jobUrl);
                jobUrl = new URL(
                        "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/load_lt_clinical_data.kjb");
                jobUrl = FileLocator.toFileURL(jobUrl);
                jobUrl = new URL(
                        "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/map_data_to_std_format.ktr");
                jobUrl = FileLocator.toFileURL(jobUrl);
                jobUrl = new URL(
                        "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/run_i2b2_load_clinical_data.ktr");
                jobUrl = FileLocator.toFileURL(jobUrl);
                jobUrl = new URL("platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/set_data_filename.ktr");
                jobUrl = FileLocator.toFileURL(jobUrl);

                job.getJobMeta().setParameterValue("DATA_LOCATION", dataType.getPath().getAbsolutePath());
                job.getJobMeta().setParameterValue("COLUMN_MAP_FILE",
                        ((ClinicalData) dataType).getCMF().getName());

                File sort = new File(dataType.getStudy().getPath().getParentFile().getAbsolutePath()
                        + File.separator + ".sort");
                if (!sort.exists()) {
                    FileUtils.forceMkdir(sort);
                }
                job.getJobMeta().setParameterValue("SORT_DIR", sort.getAbsolutePath());
                job.getJobMeta().setParameterValue("STUDY_ID", dataType.getStudy().toString());
                job.getJobMeta().setParameterValue("TOP_NODE", loadDataUI.getTopNode());
                if (((ClinicalData) dataType).getWMF() != null) {
                    job.getJobMeta().setParameterValue("WORD_MAP_FILE",
                            ((ClinicalData) dataType).getWMF().getName());
                }
                job.getJobMeta().setParameterValue("LOAD_TYPE", "I");
                job.getJobMeta().setParameterValue("TM_CZ_DB_SERVER", PreferencesHandler.getDbServer());
                job.getJobMeta().setParameterValue("TM_CZ_DB_NAME", PreferencesHandler.getDbName());
                job.getJobMeta().setParameterValue("TM_CZ_DB_PORT", PreferencesHandler.getDbPort());
                job.getJobMeta().setParameterValue("TM_CZ_DB_USER", PreferencesHandler.getTm_czUser());
                job.getJobMeta().setParameterValue("TM_CZ_DB_PWD", PreferencesHandler.getTm_czPwd());
                job.getJobMeta().setParameterValue("TM_LZ_DB_SERVER", PreferencesHandler.getDbServer());
                job.getJobMeta().setParameterValue("TM_LZ_DB_NAME", PreferencesHandler.getDbName());
                job.getJobMeta().setParameterValue("TM_LZ_DB_PORT", PreferencesHandler.getDbPort());
                job.getJobMeta().setParameterValue("TM_LZ_DB_USER", PreferencesHandler.getTm_lzUser());
                job.getJobMeta().setParameterValue("TM_LZ_DB_PWD", PreferencesHandler.getTm_lzPwd());

                job.start();
                job.waitUntilFinished();

                @SuppressWarnings("unused")
                Result result = job.getResult();
                Log4jBufferAppender appender = CentralLogStore.getAppender();
                String logText = appender.getBuffer(job.getLogChannelId(), false).toString();
                Pattern pattern = Pattern.compile(
                        ".*Finished job entry \\[run i2b2_load_clinical_data\\] \\(result=\\[true\\]\\).*",
                        Pattern.DOTALL);
                Matcher matcher = pattern.matcher(logText);
                if (matcher.matches()) {
                    String connectionString = "jdbc:oracle:thin:@" + PreferencesHandler.getDbServer() + ":"
                            + PreferencesHandler.getDbPort() + ":" + PreferencesHandler.getDbName();
                    Connection con = DriverManager.getConnection(connectionString,
                            PreferencesHandler.getTm_czUser(), PreferencesHandler.getTm_czPwd());
                    Statement stmt = con.createStatement();

                    //remove rows for study before adding new ones
                    ResultSet rs = stmt.executeQuery(
                            "select max(JOB_ID) from CZ_JOB_AUDIT where STEP_DESC='Start i2b2_load_clinical_data'");
                    int jobId;
                    if (rs.next()) {
                        jobId = rs.getInt("max(JOB_ID)");
                    } else {
                        con.close();
                        loadDataUI.setMessage("Job identifier does not exist");
                        loadDataUI.setIsLoading(false);
                        return;
                    }

                    logText += "\nOracle job id:\n" + String.valueOf(jobId);
                    con.close();
                }
                writeLog(logText);
                CentralLogStore.discardLines(job.getLogChannelId(), false);
            } catch (Exception e1) {
                e1.printStackTrace();
                loadDataUI.setMessage("Kettle exception: " + e1.getLocalizedMessage());
                loadDataUI.setIsLoading(false);
                return;
            }
            loadDataUI.setIsLoading(false);
        }
    }.start();
    this.loadDataUI.waitForThread();
    this.loadDataUI.displayMessage("Loading process is over.\n Please check monitoring step.");
    WorkPart.updateSteps();
    WorkPart.updateFiles();
}

From source file:org.apache.hive.beeline.TestBeeLineWithArgs.java

/**
 * Attempt to execute a simple script file with the -f or -i option
 * to BeeLine (or both) to  test for presence of an expected pattern
 * in the output (stdout or stderr), fail if not found.
 * Print PASSED or FAILED/*from  w w  w .  j a v a 2 s . com*/
 * @param scriptText script to test the output for
 * @param argList arguments to be passed to the script file to execute and produce output
 * @param streamType Whether match should be done against STDERR or STDOUT
 * @param expectedMatches List of Tuple's defining the pattern to match and result of matching
 * @param modes testing modes we have to run the script as
 * @throws Exception on command execution error
 */
private void testScriptFile(String scriptText, List<String> argList, OutStream streamType,
        List<Tuple<String>> expectedMatches, List<Modes> modes) throws Throwable {
    // Put the script content in a temp file
    File scriptFile = File.createTempFile(this.getClass().getSimpleName(), "temp");
    System.out.println("script file is " + scriptFile.getAbsolutePath());
    scriptFile.deleteOnExit();
    PrintStream os = new PrintStream(new FileOutputStream(scriptFile));
    os.print(scriptText);
    os.close();

    List<Tuple<Pattern>> patternsToBeMatched = Lists.transform(expectedMatches,
            new Function<Tuple<String>, Tuple<Pattern>>() {
                @Override
                public Tuple<Pattern> apply(Tuple<String> tuple) {
                    return new Tuple<>(Pattern.compile(".*" + tuple.pattern + ".*", Pattern.DOTALL),
                            tuple.shouldMatch);
                }
            });

    for (Modes mode : modes) {
        String output = mode.output(scriptFile, argList, streamType);
        for (Tuple<Pattern> patternToMatch : patternsToBeMatched) {
            Matcher m = patternToMatch.pattern.matcher(output);
            boolean matches = m.matches();
            if (patternToMatch.shouldMatch != matches) {
                //failed
                fail("Output" + output + " should" + (patternToMatch.shouldMatch ? "" : " not") + " contain "
                        + patternToMatch.pattern.pattern());
            }
        }
    }
    scriptFile.delete();
}

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

/**
 * Sprawdza rozwizanie na input/*from  www.jav  a  2 s. c om*/
 * @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:com.hp.alm.ali.idea.ui.editor.field.HTMLAreaField.java

public static String toQcHtml(String html) {
    // try to revert back constructs not compatible with QC HTML
    html = Pattern.compile("^\\s*<html>\\s*<head>.*?</head>", Pattern.DOTALL).matcher(html)
            .replaceAll("<html>");
    html = html.replaceAll("(<span )qc(style=\"font-size:8pt\">)", "$1$2");
    html = Pattern.compile("<p style=\"margin-top: 0\"(.*?</)p>", Pattern.DOTALL).matcher(html)
            .replaceAll("<div$1div>");
    return html;//from w ww  .  j  a va 2  s. c om
}

From source file:de.mpg.escidoc.services.syndication.feed.Feed.java

/**
 * Generate <code>UriMatcher</code> for the feed and list of the parameters <code>paramList</code>  
 * according to the <code>uri</code>. 
 * @param uri//from   w ww  .ja  v a2  s .  c o m
 */
public void generateUriMatcher(final String uri) {
    String result = new String(uri);

    result = escapeUri(result);

    //property regexp in uri
    String regexp = "(\\$\\{[\\w.]+?\\})";

    Matcher m = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(uri);
    while (m.find()) {
        String param = m.group(1);
        paramList.add(param);
        result = result.replaceFirst(Utils.quoteReplacement(param), "\\(.+\\)?");
    }
    setUriMatcher(result);
}