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:org.opennms.web.rest.NodeRestServiceTest.java

@Test
@JUnitTemporaryDatabase//  w w w  . j a  va 2  s . co m
public void testLimits() throws Exception {
    JAXBContext context = JAXBContext.newInstance(OnmsNodeList.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();

    // Testing POST
    for (m_nodeCounter = 0; m_nodeCounter < 20; m_nodeCounter++) {
        createNode();
    }
    String url = "/nodes";
    // Testing GET Collection
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("limit", "10");
    parameters.put("orderBy", "id");
    String xml = sendRequest(GET, url, parameters, 200);
    assertTrue(xml, xml.contains("Darwin TestMachine 9.4.0 Darwin Kernel Version 9.4.0"));
    Pattern p = Pattern.compile("<node [^>]*\\s*id=",
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
    Matcher m = p.matcher(xml);
    int count = 0;
    while (m.find()) {
        count++;
    }
    assertEquals("should get 10 nodes back", 10, count);

    // Validate object by unmarshalling
    OnmsNodeList list = (OnmsNodeList) unmarshaller.unmarshal(new StringReader(xml));
    assertEquals(Integer.valueOf(10), list.getCount());
    assertEquals(10, list.size());
    assertEquals(Integer.valueOf(20), list.getTotalCount());
    int i = 0;
    Set<OnmsNode> sortedNodes = new TreeSet<OnmsNode>(new Comparator<OnmsNode>() {
        @Override
        public int compare(OnmsNode o1, OnmsNode o2) {
            if (o1 == null && o2 == null) {
                return 0;
            } else if (o1 == null) {
                return 1;
            } else if (o2 == null) {
                return -1;
            } else {
                if (o1.getId() == null) {
                    throw new IllegalStateException("Null ID on node: " + o1.toString());
                }
                return o1.getId().compareTo(o2.getId());
            }
        }
    });
    // Sort the nodes by ID
    sortedNodes.addAll(list.getObjects());
    for (OnmsNode node : sortedNodes) {
        assertEquals(node.toString(), "TestMachine" + i++, node.getLabel());
    }
}

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

/**
 * Populate parameters with the values taken from the certain <code>uri</code> and populate
 * <code>paramHash</code> with the parameter/value paars.
 * //  w w w .ja  va2  s  .  c o  m
 * @param uri
 * @throws SyndicationException
 */
private void populateParamsFromUri(String uri) throws SyndicationException {
    Utils.checkName(uri, "Uri is empty");

    String um = getUriMatcher();

    Utils.checkName(um, "Uri matcher is empty");

    Matcher m = Pattern.compile(um, Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(uri);
    if (m.find()) {
        for (int i = 0; i < m.groupCount(); i++)
            paramHash.put((String) paramList.get(i), m.group(i + 1));
    }

    // special handling of Organizational Unit Feed
    // TODO: should be resolved other way!
    if (getUriMatcher().equals("(.+)?/syndication/feed/(.+)?/publications/organization/(.+)?")) {
        TreeMap<String, String> outm = Utils.getOrganizationUnitTree();
        String oid = (String) paramHash.get("${organizationId}");
        for (Map.Entry<String, String> entry : outm.entrySet()) {
            if (entry.getValue().equals(oid)) {
                paramHash.put("${organizationName}", entry.getKey());
            }
        }
    }

    logger.info("parameters: " + paramHash);

}

From source file:com.xebia.incubator.xebium.ExtendedSeleniumCommand.java

/**
* <p><i>(From the Selenium docs)</i></p>
* <p>//from w w w .  ja  v  a2  s .  co  m
* Various Pattern syntaxes are available for matching string values:
* </p>
* <ul>
* <li><strong>glob:</strong><em>pattern</em>: Match a string against a
* "glob" (aka "wildmat") pattern. "Glob" is a kind of limited
* regular-expression syntax typically used in command-line shells. In a
* glob pattern, "*" represents any sequence of characters, and "?"
* represents any single character. Glob patterns match against the entire
* string.</li>
* <li><strong>regexp:</strong><em>regexp</em>: Match a string using a
* regular-expression. The full power of JavaScript regular-expressions is
* available.</li>
* <li><strong>regexpi:</strong><em>regexpi</em>: Match a string using a
* case-insensitive regular-expression.</li>
* <li><strong>exact:</strong><em>string</em>:
* 
* Match a string exactly, verbatim, without any of that fancy wildcard
* stuff.</li>
* </ul>
* <p>
* If no pattern prefix is specified, Selenium assumes that it's a "glob"
* pattern.
* </p>
* <p>
* For commands that return multiple values (such as verifySelectOptions),
* the string being matched is a comma-separated list of the return values,
* where both commas and backslashes in the values are backslash-escaped.
* When providing a pattern, the optional matching syntax (i.e. glob,
* regexp, etc.) is specified once, as usual, at the beginning of the
* pattern.
* </p>
* 
* @param expected expected result, optionally prefixed
* @param actual Actual result coming from Selenium
* @return is it a match?
*/
public boolean matches(String expected, String actual) {
    boolean result;

    // Be graceful with empty strings
    if (actual == null) {
        actual = "";
    }

    if (isBooleanCommand()) {
        result = "true".equals(actual);

    } else if (expected.startsWith(REGEXP)) {
        final String regex = trim(removeStartIgnoreCase(expected, REGEXP));
        result = Pattern.compile(regex, Pattern.DOTALL).matcher(actual).matches();

    } else if (expected.startsWith(REGEXPI)) {
        final String regex = trim(removeStartIgnoreCase(expected, REGEXPI));
        result = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(actual).matches();

    } else if (expected.startsWith(EXACT)) {
        final String str = trim(removeStartIgnoreCase(expected, EXACT));
        result = str.equals(actual);

    } else {
        // "glob:"
        final String pattern;
        if (expected.startsWith(GLOB)) {
            pattern = trim(removeStartIgnoreCase(expected, GLOB));
        } else {
            pattern = expected;
        }
        result = globToRegExp(pattern).matcher(actual).matches();
    }
    if (isNegateCommand()) {
        result = !result;
    }
    return result;
}

From source file:com.morphoss.acal.service.connector.AcalRequestor.java

/**
 * Interpret the URI in the string to set protocol, host, port & path for the next request.
 * If the URI only matches a path part then protocol/host/port will be unchanged. This call
 * will only allow for path parts that are anchored to the web root.  This is used internally
 * for following Location: redirects.//w w w  .ja  v  a 2s  .  c  o  m
 *
 * This is also used to interpret the 'path' parameter to the request calls generally.
 *
 * @param uriString
 */
public void interpretUriString(String uriString) {

    if (uriString == null)
        return;

    // Match a URL, including an ipv6 address like http://[DEAD:BEEF:CAFE:F00D::]:8008/
    final Pattern uriMatcher = Pattern.compile("^(?:(https?)://)?" + // Protocol
            "(" + // host spec
            "(?:(?:[a-z0-9-]+[.]){1,7}(?:[a-z0-9-]+))" + // Hostname or IPv4 address
            "|(?:\\[(?:[0-9a-f]{0,4}:)+(?:[0-9a-f]{0,4})?\\])" + // IPv6 address
            ")" + "(?:[:]([0-9]{2,5}))?" + // Port number
            "(/.*)?$" // Path bit.
            , Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

    final Pattern pathMatcher = Pattern.compile("^(/.*)$");

    if (Constants.LOG_VERBOSE)
        Log.println(Constants.LOGV, TAG, "Interpreting '" + uriString + "'");
    Matcher m = uriMatcher.matcher(uriString);
    if (m.matches()) {
        if (m.group(1) != null && !m.group(1).equals("")) {
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found protocol '" + m.group(1) + "'");
            protocol = m.group(1);
            if (m.group(3) == null || m.group(3).equals("")) {
                port = (protocol.equals(PROTOCOL_HTTP) ? 80 : 443);
            }
        }
        if (m.group(2) != null) {
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found hostname '" + m.group(2) + "'");
            setHostName(m.group(2));
        }
        if (m.group(3) != null && !m.group(3).equals("")) {
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found port '" + m.group(3) + "'");
            port = Integer.parseInt(m.group(3));
            if (m.group(1) != null && (port == 0 || port == 80 || port == 443)) {
                port = (protocol.equals(PROTOCOL_HTTP) ? 80 : 443);
            }
        }
        if (m.group(4) != null && !m.group(4).equals("")) {
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found path '" + m.group(4) + "'");
            setPath(m.group(4));
        }
        if (!initialised)
            initialise();
    } else {
        m = pathMatcher.matcher(uriString);
        if (m.find()) {
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found relative path '" + m.group(1) + "'");
            setPath(m.group(1));
        } else {
            if (Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Using Uri class to process redirect...");
            Uri newLocation = Uri.parse(uriString);
            if (newLocation.getHost() != null)
                setHostName(newLocation.getHost());
            setPortProtocol(newLocation.getPort(), newLocation.getScheme());
            setPath(newLocation.getPath());
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found new location at '" + fullUrl() + "'");

        }
    }
}

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

/**
 * Remove any tags only valid in headers (title base meta link style)
 * /*w  w w  .  ja  v  a2s .c o m*/
 * @param data
 *        the html data.
 * @return The cleaned up data.
 */
public static String stripHeaderTags(String data) {
    if (data == null)
        return data;

    // pattern to find link/meta tags
    Pattern p = Pattern.compile("<(link|meta|title|base|style)\\s+.*?(/*>)",
            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:com.evon.injectTemplate.InjectTemplateFilter.java

private void loadContentTemplate(TemplateBean template, String domain, Integer port, boolean https,
        HttpServletRequest httpRequest) throws Exception {
    HTMLInfoBean htmlInfo = templates.get("/" + template.path);

    String sport = (port == null) ? "" : ":" + String.valueOf(port);

    String url = htmlInfo.getProtocol() + "://" + domain + sport + "/" + template.path;

    Request request = Request.Get(url);

    Enumeration<String> headerNames = httpRequest.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();

        Enumeration<String> headerValues = httpRequest.getHeaders(name);
        while (headerValues.hasMoreElements()) {
            String value = headerValues.nextElement();
            request = request.addHeader(name, value);
        }/*w w w.j a v  a2  s . co m*/
    }

    String content = request.execute().returnContent().asString();

    Pattern pattern = Pattern.compile("<INJECT[ ]{1,}selector=[\"'](.*?)[\"']/>",
            Pattern.CASE_INSENSITIVE + Pattern.DOTALL);

    Matcher matcher = pattern.matcher(content);

    List<String> selectors = new ArrayList<String>();

    while (matcher.find()) {
        String tagInject = matcher.group(0);
        String selector = matcher.group(1);
        selectors.add(selector);
        content = content.replace(tagInject, "<INJECT selector='" + selector + "'/>");
    }

    String key = null;

    if (template.cache.equals("SESSION")) {
        String cookiesNames = getCookieHashs(httpRequest);
        key = template.path + cookiesNames;
    } else {
        key = template.path;
    }

    HtmlContentBean contentBean = new HtmlContentBean();
    contentBean.setContent(content);
    contentBean.setLastAccess(System.currentTimeMillis());
    htmlContents.remove(key);
    htmlContents.put(key, contentBean);
    htmlInfo.setSelectors(selectors);
}

From source file:com.clustercontrol.agent.filecheck.FileCheck.java

private boolean matchFile(JobFileCheck check, String filename) {
    Pattern pattern = null;/*from   w ww.  ja v a2s  . c o  m*/
    String patternText = check.getFileName();
    // ?????
    pattern = Pattern.compile(patternText, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    // ???
    // pattern = Pattern.compile(patternText, Pattern.DOTALL);
    Matcher matcher = pattern.matcher(filename);

    return matcher.matches();
}

From source file:fr.sanofi.fcl4transmart.controllers.listeners.geneanalysis.LoadAnnotationListener.java

/**
 *Loads the annotation://from  w  w w.  j ava  2 s . c  o m
 *-initiate Kettle environment
 *-Find Kettle files
 *-Set Kettle parameters
 *-Calls the Kettle job
 *-Save the log file
 */
@Override
public void handleEvent(Event event) {
    this.pathToFile = this.loadAnnotationUI.getPathToFile();
    this.platformId = this.loadAnnotationUI.getPlatformId();
    this.annotationDate = this.loadAnnotationUI.getAnnotationDate();
    this.annotationRelease = this.loadAnnotationUI.getAnnotationRelease();
    this.annotationTitle = this.loadAnnotationUI.getAnnotationTitle();
    this.loadAnnotationUI.openLoadingShell();
    Thread thread = new Thread() {
        public void run() {
            if (!loadAnnotationUI.getEtlServer()) {
                try {
                    //initiate kettle environment
                    URL kettleUrl = new URL("platform:/plugin/fr.sanofi.fcl4transmart/lib/pentaho");
                    kettleUrl = FileLocator.toFileURL(kettleUrl);
                    System.setProperty("KETTLE_PLUGIN_BASE_FOLDERS", kettleUrl.getPath());
                    KettleEnvironment.init(false);

                    LanguageChoice language = LanguageChoice.getInstance();
                    language.setDefaultLocale(Locale.US);

                    //find the kettle job to initiate the loading
                    URL jobUrl = new URL(
                            "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/load_annotation.kjb");
                    jobUrl = FileLocator.toFileURL(jobUrl);
                    String 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 this job and put them in the cache
                    jobUrl = new URL(
                            "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/extract_AFFY_annotation_from_file.ktr");
                    jobUrl = FileLocator.toFileURL(jobUrl);
                    jobUrl = new URL(
                            "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/extract_GEO_annotation_from_file.ktr");
                    jobUrl = FileLocator.toFileURL(jobUrl);
                    jobUrl = new URL(
                            "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/load_annotation_to_lt.ktr");
                    jobUrl = FileLocator.toFileURL(jobUrl);
                    jobUrl = new URL(
                            "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/run_i2b2_load_annotation_deapp.ktr");
                    jobUrl = FileLocator.toFileURL(jobUrl);
                    jobUrl = new URL(
                            "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/extract_annotation_from_file.ktr");
                    jobUrl = FileLocator.toFileURL(jobUrl);
                    jobUrl = new URL(
                            "platform:/plugin/fr.sanofi.fcl4transmart/jobs_kettle/load_annotation_to_de_gpl_info.ktr");
                    jobUrl = FileLocator.toFileURL(jobUrl);

                    job.getJobMeta().setParameterValue("DATA_LOCATION", pathToFile);

                    File sort = new File(StudySelectionController.getWorkspace().getAbsoluteFile()
                            + File.separator + ".sort");
                    if (!sort.exists()) {
                        FileUtils.forceMkdir(sort);
                    }
                    job.getJobMeta().setParameterValue("SORT_DIR", sort.getAbsolutePath());
                    job.getJobMeta().setParameterValue("DATA_SOURCE", "A");
                    //check if gpl id is not empty
                    if (platformId == null) {
                        loadAnnotationUI.setMessage("Please provide the platform identifier");
                        loadAnnotationUI.setIsLoading(false);
                        return;
                    }
                    job.getJobMeta().setParameterValue("GPL_ID", platformId);
                    job.getJobMeta().setParameterValue("SKIP_ROWS", "1");
                    job.getJobMeta().setParameterValue("GENE_ID_COL", "4");
                    job.getJobMeta().setParameterValue("GENE_SYMBOL_COL", "3");
                    job.getJobMeta().setParameterValue("ORGANISM_COL", "5");
                    job.getJobMeta().setParameterValue("PROBE_COL", "2");
                    if (annotationDate != null) {
                        job.getJobMeta().setParameterValue("ANNOTATION_DATE", annotationDate);
                    }
                    if (annotationRelease != null) {
                        job.getJobMeta().setParameterValue("ANNOTATION_RELEASE", annotationRelease);
                    }
                    //check if annotation title is not empty
                    if (annotationTitle == null) {
                        loadAnnotationUI.setMessage("Please provide the annotation title");
                        loadAnnotationUI.setIsLoading(false);
                        return;
                    }
                    job.getJobMeta().setParameterValue("ANNOTATION_TITLE", annotationTitle);
                    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.getJobMeta().setParameterValue("DEAPP_DB_SERVER", PreferencesHandler.getDbServer());
                    job.getJobMeta().setParameterValue("DEAPP_DB_NAME", PreferencesHandler.getDbName());
                    job.getJobMeta().setParameterValue("DEAPP_DB_PORT", PreferencesHandler.getDbPort());
                    job.getJobMeta().setParameterValue("DEAPP_DB_USER", PreferencesHandler.getDeappUser());
                    job.getJobMeta().setParameterValue("DEAPP_DB_PWD", PreferencesHandler.getDeappPwd());

                    job.start();
                    job.waitUntilFinished(3000000);
                    job.interrupt();

                    @SuppressWarnings("unused")
                    Result result = job.getResult();

                    Log4jBufferAppender appender = CentralLogStore.getAppender();
                    String logText = appender.getBuffer(job.getLogChannelId(), false).toString();

                    Pattern pattern = Pattern.compile(
                            ".*run_i2b2_load_annotation_deapp - Dispatching started for transformation \\[run_i2b2_load_annotation_deapp\\].*",
                            Pattern.DOTALL);
                    Matcher matcher = pattern.matcher(logText);
                    if (matcher.matches()) {
                        String connection = RetrieveData.getConnectionString();
                        Connection con = DriverManager.getConnection(connection,
                                PreferencesHandler.getTm_czUser(), PreferencesHandler.getTm_czPwd());
                        Statement stmt = con.createStatement();

                        //remove rows for this study before adding new ones
                        ResultSet rs = stmt.executeQuery(
                                "select max(JOB_ID) from CZ_JOB_AUDIT where STEP_DESC='Starting i2b2_load_annotation_deapp'");
                        int jobId;
                        if (rs.next()) {
                            jobId = rs.getInt("max(JOB_ID)");
                        } else {
                            con.close();
                            loadAnnotationUI.setIsLoading(false);
                            return;
                        }

                        logText += "\nOracle job id:\n" + String.valueOf(jobId);
                        rs = stmt.executeQuery(
                                "select job_status from cz_job_master where job_id=" + String.valueOf(jobId));
                        if (rs.next()) {
                            if (rs.getString("job_status").compareTo("Running") == 0) {
                                loadAnnotationUI.setMessage(
                                        "Kettle job time out because the stored procedure is not over. Please check in a while if loading has succeed");
                                loadAnnotationUI.setIsLoading(false);
                                return;
                            }
                        }
                        rs = stmt.executeQuery(
                                "select ERROR_MESSAGE from CZ_JOB_ERROR where JOB_ID=" + String.valueOf(jobId));
                        String procedureErrors = "";
                        if (rs.next()) {
                            procedureErrors = rs.getString("ERROR_MESSAGE");
                        }
                        con.close();
                        if (procedureErrors.compareTo("") == 0) {
                            loadAnnotationUI.setMessage("Platform annotation has been loaded");
                        } else {
                            loadAnnotationUI.setMessage("Error during procedure: " + procedureErrors);
                        }
                    } else {
                        loadAnnotationUI.setMessage("Error in Kettle job: see log file");
                    }

                    writeLog(logText);
                    CentralLogStore.discardLines(job.getLogChannelId(), false);

                    //
                    loadAnnotationUI.setIsLoading(false);
                } catch (Exception e1) {
                    loadAnnotationUI.setMessage("Error: " + e1.getLocalizedMessage());
                    loadAnnotationUI.setIsLoading(false);
                    e1.printStackTrace();
                }
            } else {//use ETL server
                if (platformId == null) {
                    loadAnnotationUI.setMessage("Please provide the platform identifier");
                    loadAnnotationUI.setIsLoading(false);
                    return;
                }
                if (annotationTitle == null) {
                    loadAnnotationUI.setMessage("Please provide the annotation title");
                    loadAnnotationUI.setIsLoading(false);
                    return;
                }
                try {
                    JSch jsch = new JSch();
                    Session session = jsch.getSession(etlPreferences.getUser(), etlPreferences.getHost(),
                            Integer.valueOf(etlPreferences.getPort()));
                    session.setPassword(etlPreferences.getPass());

                    java.util.Properties config = new java.util.Properties();
                    config.put("StrictHostKeyChecking", "no");
                    config.put("PreferredAuthentications", "publickey,keyboard-interactive,password");
                    session.setConfig(config);

                    session.connect();

                    Channel channel = session.openChannel("sftp");
                    channel.connect();
                    c = (ChannelSftp) channel;

                    //try to go to the right directory for file transfer
                    String dir = etlPreferences.getFilesDirectory();
                    if (dir.compareTo("") != 0) {
                        try {
                            c.cd(dir);
                        } catch (SftpException e) {
                            loadAnnotationUI.setMessage("The file directory does not exist in this server");
                            loadAnnotationUI.setIsLoading(false);
                            return;
                        }
                    } else {
                        loadAnnotationUI.setMessage("No file directory is indicated");
                        loadAnnotationUI.setIsLoading(false);
                        return;
                    }
                    try {
                        try {
                            c.mkdir(dataType.getStudy().toString());
                        } catch (Exception exist) {
                            //normal if directory already exists
                        }
                        c.cd(dataType.getStudy().toString());
                        try {
                            c.mkdir("annotation");
                        } catch (Exception exist2) {
                            //normal if directory already exists
                        }
                        c.cd("annotation");
                    } catch (SftpException e) {
                        loadAnnotationUI.setMessage("Directory can not be created");
                        loadAnnotationUI.setIsLoading(false);
                        return;
                    }

                    File f = new File(pathToFile);
                    try {
                        c.put(f.getAbsolutePath(), ".", null, ChannelSftp.OVERWRITE);

                    } catch (SftpException e) {
                        loadAnnotationUI.setMessage("Error when transferring files");
                        loadAnnotationUI.setIsLoading(false);
                        return;
                    }

                    //run Kettle script
                    String fileLoc = "";
                    try {
                        fileLoc = c.pwd();
                    } catch (SftpException e) {
                        e.printStackTrace();
                        loadAnnotationUI.setIsLoading(false);
                        return;
                    }
                    String command = etlPreferences.getKettleDirectory() + "/kitchen.sh -norep=Y ";
                    command += "-file=" + etlPreferences.getJobsDirectory() + "/load_annotation.kjb ";
                    command += "-param:DATA_LOCATION=" + fileLoc + "  ";
                    command += "-param:SOURCE_FILENAME=" + f.getName() + " ";
                    String sortPath = "";
                    try {
                        c.cd(etlPreferences.getFilesDirectory() + "/.sort");
                        sortPath = etlPreferences.getFilesDirectory() + "/.sort";
                    } catch (Exception e) {
                        try {
                            c.cd(etlPreferences.getFilesDirectory());
                            c.mkdir(".sort");
                            sortPath = etlPreferences.getFilesDirectory() + "/.sort";
                        } catch (Exception e2) {
                            e2.printStackTrace();
                            loadAnnotationUI.setMessage("Error when creating sort directory");
                            loadAnnotationUI.setIsLoading(false);
                            return;
                        }
                    }
                    command += "-param:SORT_DIR=" + sortPath + " ";
                    command += "-param:DATA_SOURCE=A ";
                    command += "-param:GPL_ID=" + platformId + "  ";
                    command += "-param:SKIP_ROWS=1 ";
                    command += "-param:GENE_ID=4 ";
                    command += "-param:GENE_SYMBOL_COL=3 ";
                    command += "-param:ORGANISM_COL=5 ";
                    command += "-param:PROBE_COL=2 ";
                    if (annotationDate != null) {
                        command += "-param:ANNOTATION_DATE=" + annotationDate + "  ";
                    }
                    if (annotationRelease != null) {
                        command += "-param:ANNOTATION_RELEASE=" + annotationRelease + "  ";
                    }
                    command += "-param:ANNOTATION_TITLE=" + annotationTitle + "  ";
                    command += "-param:LOAD_TYPE=I ";

                    //close streams
                    channel.disconnect();

                    try {
                        channel = session.openChannel("exec");
                        ((ChannelExec) channel).setCommand(command);

                        channel.setInputStream(null);
                        InputStream in = channel.getInputStream();

                        channel.connect();

                        String out = "";
                        boolean began = false;
                        byte[] tmp = new byte[1024];
                        boolean running = true;
                        while (running) {
                            while (in.available() > 0) {
                                int i = in.read(tmp, 0, 1024);
                                if (i < 0)
                                    break;
                                out += new String(tmp, 0, i);
                                began = true;
                            }
                            if (began) {
                                Channel channel2 = session.openChannel("exec");
                                ((ChannelExec) channel2).setCommand("ps -u " + etlPreferences.getUser() + " -U "
                                        + etlPreferences.getUser() + " u");
                                channel2.setInputStream(null);
                                InputStream in2 = channel2.getInputStream();
                                channel2.connect();
                                String out2 = "";
                                byte[] tmp2 = new byte[1024];
                                while (true) {
                                    while (in2.available() > 0) {
                                        int i = in2.read(tmp2, 0, 1024);
                                        if (i < 0)
                                            break;
                                        out2 += new String(tmp2, 0, i);
                                    }
                                    if (channel2.isClosed()) {
                                        break;
                                    }
                                    try {
                                        Thread.sleep(1000);
                                    } catch (Exception ee) {
                                        ee.printStackTrace();
                                    }
                                }
                                channel2.disconnect();
                                Pattern pattern = Pattern.compile(".*load_annotation.*", Pattern.DOTALL);
                                Matcher matcher = pattern.matcher(out2);
                                if (!matcher.matches()) {
                                    running = false;
                                }
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (Exception ee) {
                                ee.printStackTrace();
                            }
                        }

                        Pattern pattern = Pattern.compile(
                                ".*run_i2b2_load_annotation_deapp - Dispatching started for transformation \\[run_i2b2_load_annotation_deapp\\].*",
                                Pattern.DOTALL);
                        Matcher matcher = pattern.matcher(out);
                        if (matcher.matches()) {
                            String connection = RetrieveData.getConnectionString();
                            Connection con = DriverManager.getConnection(connection,
                                    PreferencesHandler.getTm_czUser(), PreferencesHandler.getTm_czPwd());
                            Statement stmt = con.createStatement();

                            //remove rows for this study before adding new ones
                            ResultSet rs = stmt.executeQuery(
                                    "select max(JOB_ID) from CZ_JOB_AUDIT where STEP_DESC='Starting i2b2_load_annotation_deapp'");
                            int jobId;
                            if (rs.next()) {
                                jobId = rs.getInt("max(JOB_ID)");
                            } else {
                                con.close();
                                loadAnnotationUI.setIsLoading(false);
                                return;
                            }

                            out += "\nOracle job id:\n" + String.valueOf(jobId);
                            rs = stmt.executeQuery("select job_status from cz_job_master where job_id="
                                    + String.valueOf(jobId));
                            if (rs.next()) {
                                if (rs.getString("job_status").compareTo("Running") == 0) {
                                    loadAnnotationUI.setMessage("Kettle job timed out");
                                    loadAnnotationUI.setIsLoading(false);
                                    return;
                                }
                            }
                            rs = stmt.executeQuery("select ERROR_MESSAGE from CZ_JOB_ERROR where JOB_ID="
                                    + String.valueOf(jobId));
                            String procedureErrors = "";
                            if (rs.next()) {
                                procedureErrors = rs.getString("ERROR_MESSAGE");
                            }
                            con.close();
                            if (procedureErrors.compareTo("") == 0) {
                                loadAnnotationUI.setMessage("Platform annotation has been loaded");
                            } else {
                                loadAnnotationUI.setMessage("Error during procedure: " + procedureErrors);
                            }
                        } else {
                            loadAnnotationUI.setMessage("Error in Kettle job: see log file");
                        }
                        writeLog(out);

                        channel.disconnect();
                        session.disconnect();
                    } catch (Exception e) {
                        e.printStackTrace();
                        loadAnnotationUI.setMessage("Error when executing Kettle command");
                        loadAnnotationUI.setIsLoading(false);
                        return;
                    }

                    session.disconnect();
                    channel.disconnect();

                } catch (Exception e1) {
                    e1.printStackTrace();
                    loadAnnotationUI.setMessage("Error when transferring files");
                    loadAnnotationUI.setIsLoading(false);
                    return;
                }
            }
            loadAnnotationUI.setIsLoading(false);
        }
    };
    thread.start();
    this.loadAnnotationUI.waitForThread();
    WorkPart.updateSteps();
    WorkPart.updateFiles();
}

From source file:de.undercouch.bson4jackson.BsonGeneratorTest.java

@Test
public void patterns() throws Exception {
    Pattern pattern = Pattern.compile("a.*a", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Map<String, Object> data = new LinkedHashMap<String, Object>();
    data.put("pattern", pattern);

    BSONObject obj = generateAndParse(data);

    Pattern result = (Pattern) obj.get("pattern");
    assertNotNull(result);//from  ww  w.ja v a  2 s .  com
    assertEquals(pattern.pattern(), result.pattern());
    assertEquals(pattern.flags(), result.flags());
}

From source file:com.thoughtworks.go.domain.materials.git.GitCommandTest.java

@Test
void shouldOutputSubmoduleRevisionsAfterUpdate() throws Exception {
    GitRepoContainingSubmodule submoduleRepos = new GitRepoContainingSubmodule(temporaryFolder);
    submoduleRepos.addSubmodule(SUBMODULE, "sub1");
    GitCommand gitWithSubmodule = new GitCommand(null, createTempWorkingDirectory(),
            GitMaterialConfig.DEFAULT_BRANCH, false, null);
    gitWithSubmodule.clone(inMemoryConsumer(), submoduleRepos.mainRepo().getUrl());
    InMemoryStreamConsumer outConsumer = new InMemoryStreamConsumer();
    gitWithSubmodule.resetWorkingDir(outConsumer, new StringRevision("HEAD"), false);
    Matcher matcher = Pattern
            .compile(".*^\\s[a-f0-9A-F]{40} sub1 \\(heads/master\\)$.*", Pattern.MULTILINE | Pattern.DOTALL)
            .matcher(outConsumer.getAllOutput());
    assertThat(matcher.matches()).isTrue();
}