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:bala.padio.Player.java

private String getStreamUrl(String url) {
    String streamUrl = url;//w w w .j a v a  2s. co m
    if (url.toLowerCase().endsWith(".pls")) {
        String plsFile = Settings.DownloadFromUrl(url);
        Log.i(TAG, "Pls file: " + plsFile);
        if (plsFile == null) {
            Log.e(TAG, "Failed to download: " + url);
        } else {
            // using regex to find the File field in the pls file
            Pattern regex = Pattern.compile("File1[\\w]*=([^\\n]*)", Pattern.DOTALL);
            Matcher regexMatcher = regex.matcher(plsFile);
            if (regexMatcher.find()) {
                streamUrl = regexMatcher.group(1);
                streamUrl = streamUrl.trim();
            } else {
                Log.e(TAG, "Stream playerUrl not found in the pls file");
            }
        }
    }
    Log.d(TAG, "Stream playerUrl: " + streamUrl);
    return streamUrl;
}

From source file:org.openmrs.module.adminui.TestUtils.java

/**
 * Tests whether the substring is contained in the actual string. Allows for inclusion of
 * regular expressions in the substring. Ignores white space. Ignores capitalization.
 */// w  w  w .j av a 2  s .co m
public static void assertFuzzyContains(String substring, String actual) {
    if (substring == null) {
        return;
    }
    if (actual == null) {
        Assert.fail(substring + " is not contained in " + actual);
    }

    if (!Pattern.compile(stripWhitespaceAndConvertToLowerCase(substring), Pattern.DOTALL)
            .matcher(stripWhitespaceAndConvertToLowerCase(actual)).find()) {
        Assert.fail(substring + " is not contained in " + actual);
    }
}

From source file:aurelienribon.utils.TemplateManager.java

/**
 * Processes the variables over the given string, and returns the result.
 *//*from ww w.j  a va2 s  .  c o m*/
public String process(String input) {
    for (String var : replacements.keySet()) {
        input = input.replaceAll("@\\{" + var + "\\}", replacements.get(var));
    }

    {
        Pattern p = Pattern.compile("@\\{ifdef (" + varPattern + ")\\}(.*?)@\\{endif\\}", Pattern.DOTALL);
        Matcher m = p.matcher(input);
        StringBuffer sb = new StringBuffer();

        while (m.find()) {
            String var = m.group(1);
            String content = m.group(2);
            if (replacements.containsKey(var))
                m.appendReplacement(sb, content);
            else
                m.appendReplacement(sb, "");
        }

        m.appendTail(sb);
        input = sb.toString();
    }

    {
        Pattern p = Pattern.compile("@\\{ifndef (" + varPattern + ")\\}(.*?)@\\{endif\\}", Pattern.DOTALL);
        Matcher m = p.matcher(input);
        StringBuffer sb = new StringBuffer();

        while (m.find()) {
            String var = m.group(1);
            String content = m.group(2);
            if (!replacements.containsKey(var))
                m.appendReplacement(sb, content);
            else
                m.appendReplacement(sb, "");
        }

        m.appendTail(sb);
        input = sb.toString();
    }

    return input;
}

From source file:io.github.microcks.web.SoapController.java

@RequestMapping(value = "/{service}/{version}", method = RequestMethod.POST)
public ResponseEntity<?> execute(@PathVariable("service") String serviceName,
        @PathVariable("version") String version,
        @RequestParam(value = "validate", required = false) Boolean validate,
        @RequestParam(value = "delay", required = false) Long delay, @RequestBody String body) {
    log.info("Servicing mock response for service [{}, {}]", serviceName, version);
    log.debug("Request body: " + body);

    long startTime = System.currentTimeMillis();

    // Retrieve service and correct operation.
    Service service = serviceRepository.findByNameAndVersion(serviceName, version);
    Operation rOperation = null;//from   w w w.  j a  v a2s.c  o  m
    for (Operation operation : service.getOperations()) {
        // Enhancement : try getting operation from soap:body directly!
        String openingPattern = "(.*):Body>(\\s*)<(\\w+):" + operation.getInputName() + ">(.*)";
        String closingPattern = "(.*)</(\\w+):" + operation.getInputName() + ">(\\s*)</(\\w+):Body>(.*)";
        Pattern op = Pattern.compile(openingPattern, Pattern.DOTALL);
        Pattern cp = Pattern.compile(closingPattern, Pattern.DOTALL);

        if (op.matcher(body).matches() && cp.matcher(body).matches()) {
            rOperation = operation;
            break;
        }
    }

    if (rOperation != null) {
        log.debug("Found a valid operation with rules: {}", rOperation.getDispatcherRules());

        if (validate != null && validate) {
            log.debug("Soap message validation is turned on, validating...");
            try {
                List<XmlError> errors = SoapMessageValidator.validateSoapMessage(rOperation.getInputName(),
                        service.getXmlNS(), body, resourceUrl + service.getName() + "-" + version + ".wsdl",
                        true);
                log.debug("SoapBody validation errors: " + errors.size());

                // Return a 400 http code with errors.
                if (errors != null && errors.size() > 0) {
                    return new ResponseEntity<Object>(errors, HttpStatus.BAD_REQUEST);
                }
            } catch (Exception e) {
                log.error("Error during Soap validation", e);
            }
        }

        Response response = null;
        String dispatchCriteria = null;

        // Depending on dispatcher, evaluate request with rules.
        if (DispatchStyles.QUERY_MATCH.equals(rOperation.getDispatcher())) {
            dispatchCriteria = getDispatchCriteriaFromXPathEval(rOperation, body);

        } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) {
            dispatchCriteria = getDispatchCriteriaFromScriptEval(rOperation, body);
        }

        log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
        List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(
                IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
        if (!responses.isEmpty()) {
            response = responses.get(0);
        }

        // Setting delay to default one if not set.
        if (delay == null && rOperation.getDefaultDelay() != null) {
            delay = rOperation.getDefaultDelay();
        }

        if (delay != null && delay > -1) {
            log.debug("Mock delay is turned on, waiting if necessary...");
            long duration = System.currentTimeMillis() - startTime;
            if (duration < delay) {
                Object semaphore = new Object();
                synchronized (semaphore) {
                    try {
                        semaphore.wait(delay - duration);
                    } catch (Exception e) {
                        log.debug("Delay semaphore was interrupted");
                    }
                }
            }
            log.debug("Delay now expired, releasing response !");
        }

        // Publish an invocation event before returning.
        MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version,
                response.getName(), new Date(startTime), startTime - System.currentTimeMillis());
        applicationContext.publishEvent(event);
        log.debug("Mock invocation event has been published");

        // Set Content-Type to "text/xml".
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.valueOf("text/xml;charset=UTF-8"));
        return new ResponseEntity<Object>(response.getContent(), responseHeaders, HttpStatus.OK);
    }

    return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}

From source file:net.palette_software.pet.restart.HelperHttpClient.java

static List<BalancerManagerManagedWorker> getWorkersFromHtml(String body, String clusterName,
        String jmxObjectName) throws Exception {

    String regex;//from   w ww .  ja  v a 2 s  .  c  om
    Pattern p;
    String nonce = "";
    String[] bodySlpit;
    Matcher m;
    int jmxPort;

    //search for the cluster's nonce string
    regex = "<h3>.*&nonce=([^\"]+)\">balancer://" + clusterName + "</a>.*";
    p = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);
    bodySlpit = body.split("\n");
    for (String s : bodySlpit) {
        m = p.matcher(s);
        if (m.matches()) {
            nonce = m.group(1);
            break;
        }
    }

    if (nonce.equals("")) {
        throw new Exception("Cannot found the worker load balancer in balancer-manager");
    }

    List<BalancerManagerManagedWorker> workers = new ArrayList<>();

    //Search for the Workers' name
    for (String s : bodySlpit) {
        regex = "<td><a href=\"/balancer-manager\\?b=" + clusterName + "&w=([^&]+)&nonce=" + nonce
                + "[^<]*</a></td><td>([^<]+)?.*";
        p = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);
        m = p.matcher(s);
        if (m.matches()) {
            String memberName = m.group(1);
            String route = m.group(2);

            regex = ".*:([0-9]+)";
            p = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);
            m = p.matcher(memberName);

            if (!m.matches()) {
                throw new Exception("Cannot found the workers' port");
            }

            //check the jmx ports if we need it
            if (!CliControl.FORCE_RESTARTS && !Objects.equals(jmxObjectName, "")) {

                //calculate JMX port
                jmxPort = Integer.parseInt(m.group(1)) + 300;

                //check if port exists
                try (HelperJmxClient jmxClient = new HelperJmxClient()) {

                    int count = 0;
                    String error = "";
                    while (count++ < 3) {
                        String jMXServiceURL = "service:jmx:rmi:///jndi/rmi://:" + jmxPort + "/jmxrmi";
                        jmxClient.connectService(jMXServiceURL);
                        if (!jmxClient.checkBeanExists(jmxObjectName)) {
                            error = "Cannot found the required MBean " + jMXServiceURL + ":" + jmxObjectName;
                            HelperLogger.loggerStdOut.info(
                                    error + "\nRetrying after " + CliControl.WAIT_AFTER_ERROR + " seconds...");
                            CliControl.sleep(CliControl.WAIT_AFTER_ERROR);
                        } else {
                            error = "";
                            break;
                        }
                    }
                    if (!Objects.equals(error, "")) {
                        throw new Exception(error);
                    }

                }
            } else {
                jmxPort = -1;
            }

            //add Worker into workers
            if (Objects.equals(clusterName, "vizqlserver-cluster")) {
                workers.add(new WorkerVizql(memberName, route, nonce, jmxPort));
            } else if (Objects.equals(clusterName, "dataserver-cluster")) {
                workers.add(new WorkerDataServer(memberName, route, nonce, jmxPort));
            } else if (Objects.equals(clusterName, "local-vizportal")) {
                workers.add(new WorkerVizportal(memberName, route, nonce, jmxPort));
            }
        }
    }
    return workers;
}

From source file:com.quinsoft.zeidon.standardoe.WriteOiToStream.java

void writeToStream() {
    // Compile a regex that will search for special printable chars later on.
    Pattern specialChars = Pattern
            .compile(".*[\\n\\r" + PortableFileReader.STRING_STORED_AS_BLOB_REGEX + "]+.*", Pattern.DOTALL);

    // Since we use it a lot, create a local value.
    boolean writeIncremental = flags.contains(WriteOiFlags.fINCREMENTAL);

    // Used to create the link statements at the end.
    int hierIndex = 0;

    // Initialize instance flags that we'll use during the write.
    for (EntityInstanceImpl ei : view.getObjectInstance().getEntities()) {
        ei.setWritten(false);/*from  www  . ja  va 2  s  .c  om*/
        ei.setRecordOwner(false);
        ei.setHierIndex(-1);
    }

    long lastLinked = -1;

    String erDate = "0";
    String incremental = writeIncremental ? "1" : "0";
    String compressed = "0";
    String optimisticOIs = "0";
    String attribFlags = writeIncremental ? "1" : "0";

    String header = String.format("z%s%s%s%s%sZeidon    %8s %s %s", erDate, incremental, compressed,
            optimisticOIs, attribFlags, name, view.getViewOd().getName().toUpperCase(),
            DATE_FORMATTER.print(new DateTime()));
    try {
        writeln(header);

        if (writeIncremental) {
            long flags = 0;
            if (view.getObjectInstance().isLocked())
                flags |= META_OI_LOCKED;

            if (view.getObjectInstance().isReadOnly())
                flags |= META_OI_READONLY;

            writeln("mOIFLAGS    %x", flags);
        }

        // Loop through the entities.  We can't use the iterator because the inner loop
        // object may skip some.
        for (EntityInstanceImpl ei = view.getObjectInstance().getRootEntityInstance(); ei != null; ei = ei
                .getNextHier()) {
            ViewEntity viewEntity = ei.getViewEntity();
            if (ei.isHidden() && !writeIncremental) {
                // EI is hidden and we're not writing incrementals, so skip this one
                // and all its children.
                ei = ei.getLastChildHier();
                continue;
            }

            ei.setHierIndex(hierIndex++);

            // Write out entity name and instance flags.
            write("e%-9s %d", viewEntity.getName(), ei.getLevel());
            if (writeIncremental) {
                // Write the incremental flags.
                write(",%d", ei.getInstanceFlags());
            }
            writeln();

            if (flags.contains(WriteOiFlags.fENTITY_TAGS) || ei.getTag() != null) {
                String tag = ei.getTag();
                if (StringUtils.isBlank(tag))
                    tag = Integer.toHexString(ei.hashCode());
                writeln("mETAG      %s", tag);
            }

            if (flags.contains(WriteOiFlags.fENTITY_KEYS)) {
                writeln("mEKEY      %d", ei.getEntityKey());
            }

            // If the EI has already been written (this means it's linked to another
            // EI that has already been written) and it has no non-persist record,
            // then we don't need to write it's attribute values.
            if (ei.isWritten()) {
                lastLinked = ei.getHierIndex();
                ei.setWritten(true);
            } else {
                // The ei is linked and it hasn't been written so it must be the record
                // owner.
                ei.setRecordOwner(true);

                // Set the written flag for all the linked instances that belong
                // to this OI.
                for (EntityInstanceImpl linked : ei.getAllLinkedInstances()) {
                    if (linked.getObjectInstance() == view.getObjectInstance())
                        linked.setWritten(true);
                }
            }

            // Loops through all non-null attributes.
            for (ViewAttribute viewAttrib : ei.getNonNullAttributeList()) {
                // Don't bother if the attribute is derived.
                if (viewAttrib.isDerived())
                    continue;

                if (flags.contains(WriteOiFlags.fKEYS_ONLY) && !viewAttrib.isKey())
                    continue;

                // If this entity is the one that was most recently flagged as linked, don't
                // write persistent attributes -- they were already written for a linked
                // instance.
                if (viewAttrib.isPersistent() && ei.getHierIndex() == lastLinked)
                    continue;

                // Write the attribute flags if they aren't 0.
                String flags = "";
                if (writeIncremental && ei.getInternalAttribute(viewAttrib).getAttributeFlags() != 0)
                    flags = String.format(",%x", ei.getInternalAttribute(viewAttrib).getAttributeFlags());

                write("a%-9s ", viewAttrib.getName() + flags);

                if (viewAttrib.getType() == InternalType.BLOB) {
                    Blob blob = (Blob) ei.getInternalAttributeValue(viewAttrib);
                    byte[] bytes = blob.getBytes();
                    writeln("%d", bytes.length);
                    write(bytes.toString());
                } else {
                    String value = ei.getStringFromAttribute(viewAttrib);

                    // If the attribute type is a string then check to see if it contains "special"
                    // characters that interfere with normal attribute values, like "\n".
                    if (viewAttrib.getType() == InternalType.STRING
                            && (value.length() > 254 || specialChars.matcher(value).matches())) {
                        writeln("%c%d", PortableFileReader.STRING_STORED_AS_BLOB, value.length());
                    }

                    writeln("%s", value);
                }

            } // for each attribute...

            // Write a blank line just to look pretty.
            writeln();

        } // for each entity instance...

        // If any intra-object linked instances were found, create
        // link records now.
        if (lastLinked > -1) {
            for (EntityInstanceImpl ei : view.getObjectInstance().getEntities()) {
                // If we've gone past the last linked EI we're done.
                if (ei.getHierIndex() > lastLinked)
                    break;

                // If index is -1 it wasn't written.
                if (ei.getHierIndex() == -1)
                    continue;

                // If the entity is the record owner then we don't write link cards.
                // Link records are written for the non-record owner.
                if (ei.isRecordOwner())
                    continue;

                synchronized (ei.getAllLinkedInstances()) {
                    for (EntityInstanceImpl linked : ei.getAllLinkedInstances()) {
                        if (linked == ei)
                            continue; // Don't write a link record for ourself.

                        if (linked.getObjectInstance() == view.getObjectInstance() && linked.isRecordOwner()) {
                            assert ei.getHierIndex() != linked.getHierIndex() : "Mismatched record owners.";
                            assert ei.getViewEntity().getErEntityToken() == linked.getViewEntity()
                                    .getErEntityToken() : "Mismatched entity tokens";

                            writeln("i%-9d %d", ei.getHierIndex(), linked.getHierIndex());
                            break;
                        }
                    }
                }
            } // for each entity instance...
        } // if ( lastLinked > -1 )...

        // Indicate that the OI is done.
        writeln("ZEND");
    } catch (Throwable e) {
        throw ZeidonException.wrapException(e);
    }
}

From source file:de.felixschulze.maven.plugins.xcode.GHUnitTestMojo.java

/**
 * Execute the xcode command line utility.
 *//*from w  w w .j  av  a2s  . c o m*/
public void execute() throws MojoExecutionException {

    if (executeGHUnitTests) {

        if (!iosSimCommandLine.exists()) {
            throw new MojoExecutionException(
                    "Invalid path for ios-sim: " + iosSimCommandLine.getAbsolutePath());
        }
        if (appName == null) {
            throw new MojoExecutionException("AppName must be defined.");
        }

        if (!xcodeSdk.contains("iphonesimulator")) {
            throw new MojoExecutionException("GHUnit-Tests can only run on simulator");
        }

        File appDirectory = new File(buildDirectory, xcodeConfiguration + "-iphonesimulator");
        File testResultsDirectory = new File(buildDirectory, "test-results");

        File appFile = new File(appDirectory, appName + ".app");

        CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
        executor.setLogger(this.getLog());
        List<String> commands = new ArrayList<String>();

        commands.add("launch");
        commands.add(appFile.getAbsolutePath());
        if (testDevice != null) {
            commands.add("--family");
            commands.add(testDevice);
        }

        if (!testNoAutoExit) {
            commands.add("--setenv");
            commands.add("GHUNIT_AUTOEXIT=YES");
        }

        if (teamCityLog) {
            commands.add("--setenv");
            commands.add("GHUNIT_AUTORUN=1");
            commands.add("--setenv");
            commands.add("WRITE_JUNIT_XML=1");
            commands.add("--setenv");
            commands.add("JUNIT_XML_DIR=" + testResultsDirectory.getAbsolutePath());
        }

        if (retinaDevice) {
            commands.add("--retina");
        }

        if (tallDevice) {
            commands.add("--tall");
        }

        ProcessHelper.killSimulatorProcess(getLog());

        try {
            getLog().info(iosSimCommandLine.getAbsolutePath() + " " + commands.toString());
            executor.executeCommand(iosSimCommandLine.getAbsolutePath(), commands, false, true);
            final String errorOut = executor.getStandardError();

            String regexSimulatorTimeOut = ".*Simulator session timed out.(.*)";
            Boolean sessionTimedOut = Pattern.compile(regexSimulatorTimeOut, Pattern.DOTALL).matcher(errorOut)
                    .matches();
            if (sessionTimedOut) {
                if (teamCityLog) {
                    getLog().error(TeamCityHelper.createBuildStatusFailureLog("Simulator session timed out."));
                }
                getLog().error("Simulator session timed out.");
                throw new MojoExecutionException("Simulator session timed out.");
            }

            String regex = ".*Executed [0-9]* of [0-9]* tests, with [0-9]* failures in [0-9]*.[0-9]* seconds(.*)";
            Boolean success = Pattern.compile(regex, Pattern.DOTALL).matcher(errorOut).matches();
            if (!success) {
                if (teamCityLog) {
                    getLog().error(TeamCityHelper
                            .createBuildStatusFailureLog("Tests failed - The app may be crashed"));
                }
                getLog().error("Tests failed - The app may be crashed");
                throw new MojoExecutionException("Tests failed - The app may be crashed");
            }
        } catch (ExecutionException e) {
            throw new MojoExecutionException("Error while executing: ", e);
        }

        //Test results
        if (teamCityLog) {
            String[] extension = { "xml" };
            Iterator<File> fileIterator = FileUtils.iterateFiles(testResultsDirectory, extension, true);
            while (fileIterator.hasNext()) {
                File testXml = fileIterator.next();
                getLog().info("##teamcity[importData type='junit' path='" + testXml.getAbsolutePath() + "']");
            }

        }

        //Coverage
        if (generateCoverageReport) {

            if (!lcovCommandLine.exists()) {
                throw new MojoExecutionException("Invalid path for lcov: " + lcovCommandLine.getAbsolutePath());
            }
            if (!genHtmlCommandLine.exists()) {
                throw new MojoExecutionException(
                        "Invalid path for genhtml: " + genHtmlCommandLine.getAbsolutePath());
            }

            commands = new ArrayList<String>();
            commands.add("--directory");

            File coverageObjectsDir = buildDirectory;

            String buildFolderName;
            if (coverageAppName != null) {
                buildFolderName = coverageAppName + ".build";
            } else {
                buildFolderName = appName + ".build";
            }
            String[] directoryStructure = { xcodeProject.getName().replace(".xcodeproj", ".build"),
                    xcodeConfiguration + "-iphonesimulator", buildFolderName, "Objects-normal", "i386" };
            for (String currentDir : directoryStructure) {
                coverageObjectsDir = new File(coverageObjectsDir.getAbsolutePath(), currentDir);
            }

            commands.add(coverageObjectsDir.getAbsolutePath());
            commands.add("--capture");
            commands.add("--output-file");

            File coverageOutPutFile = new File(buildDirectory, "main.info");
            commands.add(coverageOutPutFile.getAbsolutePath());

            commands.add("-b");
            commands.add(basedir);

            File coverageTargetOutPutFile = new File(buildDirectory, appName + ".info");

            getLog().info(lcovCommandLine.getAbsolutePath() + " " + commands.toString());

            try {
                executor.executeCommand(lcovCommandLine.getAbsolutePath(), commands, false);

                commands = new ArrayList<String>();
                commands.add("-o");
                commands.add(coverageTargetOutPutFile.getAbsolutePath());

                commands.add("--extract");
                commands.add(coverageOutPutFile.getAbsolutePath());
                commands.add("'*" + coverageTarget + "/*'");

                getLog().info(lcovCommandLine.getAbsolutePath() + " " + commands.toString());
                executor.executeCommand(lcovCommandLine.getAbsolutePath(), commands, false);

                final String errorOut = executor.getStandardOut();

                String regex = ".*.*lines......: ([0-9]*.[0-9])*% \\(([0-9]*) of ([0-9]*) lines\\)(.*)";
                Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
                Matcher matcher = pattern.matcher(errorOut);

                while (matcher.find()) {
                    if (teamCityLog) {
                        getLog().info("##teamcity[buildStatisticValue key='CodeCoverageL' value='"
                                + matcher.group(1) + "'");
                        getLog().info("##teamcity[buildStatisticValue key='CodeCoverageAbsLCovered' value='"
                                + matcher.group(2) + "'");
                        getLog().info("##teamcity[buildStatisticValue key='CodeCoverageAbsLTotal' value='"
                                + matcher.group(3) + "'");
                    }
                }
            } catch (ExecutionException e) {
                throw new MojoExecutionException("Error while executing lcov: ", e);
            }

            //Generate HTML Report
            File coverageReportDir = new File(new File(buildDirectory, "artifacts"), "coverage");
            coverageReportDir.mkdirs();

            try {
                commands = new ArrayList<String>();
                commands.add(coverageTargetOutPutFile.getAbsolutePath());
                commands.add("--prefix");
                commands.add(basedir);
                commands.add("--output-directory");
                commands.add(coverageReportDir.getAbsolutePath());

                getLog().info(genHtmlCommandLine.getAbsolutePath() + " " + commands.toString());
                executor.executeCommand(genHtmlCommandLine.getAbsolutePath(), commands, false);
            } catch (ExecutionException e) {
                throw new MojoExecutionException("Error while executing genhtml: ", e);
            }
        }
        ProcessHelper.killSimulatorProcess(getLog());

    } else {
        getLog().info("Skipping GHUnit-Tests.");
    }
}

From source file:apps.ParsedPost.java

private static String replace(String src, String pat, String repl, boolean bIgnoreCase) {
    Pattern p = bIgnoreCase/*w  w  w . j  ava 2 s  .  c o m*/
            ? Pattern.compile(pat, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL)
            : Pattern.compile(pat, Pattern.MULTILINE | Pattern.DOTALL);
    Matcher m = p.matcher(src);

    return m.replaceAll(repl);
}

From source file:org.auraframework.integration.test.http.resource.BootstrapTest.java

@SuppressWarnings("unchecked")
@Test/*from   w  ww . j a v  a  2 s  .  c  om*/
public void testWriteSetsOkResponseWithErrorPayloadWhenTokenValidationFails() throws Exception {
    // Arrange
    if (contextService.isEstablished()) {
        contextService.endContext();
    }
    DefDescriptor<ApplicationDef> appDesc = addSourceAutoCleanup(ApplicationDef.class,
            "<aura:application></aura:application>");
    AuraContext context = contextService.startContext(AuraContext.Mode.PROD, AuraContext.Format.MANIFEST,
            AuraContext.Authentication.AUTHENTICATED, appDesc);

    HttpServletRequest request = mock(HttpServletRequest.class);
    MockHttpServletResponse response = new MockHttpServletResponse();

    ConfigAdapter configAdapter = mock(ConfigAdapter.class);

    Bootstrap bootstrap = getBootstrap();
    bootstrap.setConfigAdapter(configAdapter);

    // Force token validation to fail
    when(configAdapter.validateBootstrap(anyString())).thenReturn(false);

    // Act
    bootstrap.write(request, response, context);

    // Assert
    // JWT token failure returns 2xx response code with error payload so browser executes it
    assertEquals(HttpStatus.SC_OK, response.getStatus());

    /*
     * Expected appBootstrap object
     * window.Aura.appBootstrap = {
     *     "error":{
     *          "message":"Invalid jwt parameter"
     *     }
     * };
     */
    String content = response.getContentAsString();
    Pattern pattern = Pattern.compile("appBootstrap = (\\{.*\\});", Pattern.DOTALL);
    Matcher matcher = pattern.matcher(content);
    assertTrue("Failed to find appBootstrap in response: " + content, matcher.find());

    Map<String, Object> appBootstrap = (Map<String, Object>) new JsonReader().read(matcher.group(1));
    Map<String, Object> error = (Map<String, Object>) appBootstrap.get("error");

    String actualMessage = error.get("message").toString();
    // refer to the message in Bootstrap.write()
    String expectedMessage = "Invalid jwt parameter";
    assertThat("Failed to find expected message: " + content, actualMessage, containsString(expectedMessage));
}

From source file:damo.three.ie.prepay.UsageFetcher.java

/**
 * Begin fetching the usage/*from w ww  . ja va 2 s.  co m*/
 */
public JSONArray getUsages() throws IOException, AccountException, JSONException, PrepayException {

    // Some change on 22-08-2014 means that when we have cookies cached from previous login and this login session
    // is expired, if we perform a login and go through login steps, we are greeted with login page again. Clear
    // cookies prior to prevent this.
    try {
        ThreeHttpClient.getInstance(context).getHttpClient().getCookieStore().clear();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
    // Attempt to log in.
    pageContent = processRequest.process(Constants.MY3_ACCOUNT_PAGE);
    Log.d(Constants.TAG, "using: my3account.three.ie");

    // Were we brought to the login page? If so, login. We sometimes skip this if our cookie still holds a valid
    // session.
    if (pageContent.contains("<label for=\"username\" class=\"portlet-form-input-label\">")) {
        Pattern p1 = Pattern.compile(Constants.LOGIN_TOKEN_REGEX, Pattern.DOTALL);
        Matcher m1 = p1.matcher(pageContent);
        if (m1.matches()) {
            Log.d(Constants.TAG, "Logging in...");
            addPropertyToPostData("lt", m1.group(1));
            pageContent = processRequest.process(Constants.MY3_ACCOUNT_PAGE, postData);
            if (pageContent.contains("Sorry, you've entered an invalid")) {
                throw new AccountException("Invalid 3 mobile number or password.");
            } else if (pageContent.contains("You have entered your login details incorrectly too many times")) {
                throw new AccountException("Account is temporarily disabled due to too many incorrect logins. "
                        + "Please try again later.");
            }
        }
    }

    // We end up here if we have logged in, or if our cookie was still valid.
    if (pageContent.contains("here</a> to access the service you requested.</p>")) {
        Pattern p1 = Pattern.compile(Constants.MY3_SERVICE_REGEX, Pattern.DOTALL);
        Matcher m1 = p1.matcher(pageContent);
        if (m1.matches()) {
            pageContent = processRequest.process(m1.group(1));
        }

        //As of 22-08-2014, this page comes up a second time, with a new token. This time without SSL!
        if (pageContent.contains("here</a> to access the service you requested.</p>")) {
            Pattern p2 = Pattern.compile(Constants.MY3_SERVICE_REGEX, Pattern.DOTALL);
            Matcher m2 = p2.matcher(pageContent);
            if (m2.matches()) {
                pageContent = processRequest.process(m2.group(1));
            }
        }

        if (pageContent.contains("<p><strong>Your account balance.</strong></p>")) {
            parseUsage();
        } else {
            if (!runningInBackground) {
                reportErrorFetchingUsage();
            }
        }

    } else if (pageContent.contains("This service is currently unavailable. Please try again later.")) {
        // Known service error from three.
        throw new PrepayException("my3account.three.ie is reporting: \"This service is currently unavailable. "
                + "Please try again later.\"");
    } else {
        // Unknown response
        if (!runningInBackground) {
            reportErrorFetchingUsage();
        }
    }
    return jsonArray;
}