Example usage for org.apache.commons.lang3 StringUtils difference

List of usage examples for org.apache.commons.lang3 StringUtils difference

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils difference.

Prototype

public static String difference(final String str1, final String str2) 

Source Link

Document

Compares two Strings, and returns the portion where they differ.

Usage

From source file:com.baasbox.service.user.FriendShipService.java

public static List<ODocument> getFollowing(String username, QueryParams criteria) throws SqlInjectionException {
    OUser me = UserService.getOUserByUsername(username);
    Set<ORole> roles = me.getRoles();
    List<String> usernames = roles.parallelStream().map(ORole::getName)
            .filter((x) -> x.startsWith(RoleDao.FRIENDS_OF_ROLE))
            .map((m) -> StringUtils.difference(RoleDao.FRIENDS_OF_ROLE, m)).collect(Collectors.toList());
    if (username.isEmpty()) {
        return Collections.emptyList();
    } else {//from  w  w w.j a  v a 2  s  . c  o m
        List<ODocument> followers = UserService.getUserProfileByUsernames(usernames, criteria);
        return followers;
    }

}

From source file:ee.ria.xroad.proxy.testsuite.testcases.SplitHeaderMessage.java

@SuppressWarnings("unchecked")
private static void validateFieldValue(Message message) throws Exception {
    SoapMessageImpl msg = (SoapMessageImpl) new SoapParserImpl().parse(message.getContentType(),
            new ByteArrayInputStream(((SoapMessageImpl) message.getSoap()).getBytes()));
    String value = null;//  www.j a v  a 2s. c  o  m
    Iterator<SOAPHeaderElement> h = msg.getSoap().getSOAPHeader().examineAllHeaderElements();
    while (h.hasNext()) {
        SOAPHeaderElement header = h.next();
        if (header.getElementName().getLocalName().equals("issue")) {
            value = header.getValue();
        }
    }
    if (!StringUtils.equals(EXPECTED_VALUE, value)) {
        String diff = StringUtils.difference(EXPECTED_VALUE, value);
        throw new Exception(
                "Unexpected field value (difference starting at" + " index : " + value.indexOf(diff) + ")");
    }
}

From source file:com.orange.ocara.model.export.docx.DocxWriter.java

/**
 * To zip a directory./*from  w ww .  jav a2  s.com*/
 *
 * @param rootPath  root path
 * @param directory directory
 * @param zos       ZipOutputStream
 * @throws IOException
 */
private void zipDirectory(String rootPath, File directory, ZipOutputStream zos) throws IOException {
    //get a listing of the directory content
    File[] files = directory.listFiles();

    //loop through dirList, and zip the files
    for (File file : files) {
        if (file.isDirectory()) {
            zipDirectory(rootPath, file, zos);
            continue;
        }

        String filePath = FilenameUtils.normalize(file.getPath(), true);
        String fileName = StringUtils.difference(rootPath, filePath);

        fileName = fileName.replaceAll("\\[_\\]", "_").replaceAll("\\[.\\]", ".");

        //create a FileInputStream on top of file
        ZipEntry anEntry = new ZipEntry(fileName);
        zos.putNextEntry(anEntry);

        FileUtils.copyFile(file, zos);
    }
}

From source file:com.versatus.jwebshield.filter.SecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr());
    logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo());
    logger.debug("doFilter: queryString=" + httpReq.getQueryString());
    logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString());
    logger.debug("doFilter: method=" + httpReq.getMethod());
    logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin"));
    logger.info("doFilter: Referer=" + httpReq.getHeader("Referer"));
    logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName));

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);
    HttpSession session = httpReq.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;//from w  w  w . j  a v a 2 s. c  o  m
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }
    // check CSRF cookie/header
    boolean csrfHeaderPassed = false;
    String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName);
    if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) {
        String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\"");
        logger.debug("doFilter: csrfHeader after decoding" + csrfHeader);
        Cookie[] cookies = httpReq.getCookies();
        for (Cookie c : cookies) {
            String name = c.getName();

            if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) {

                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());

                logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue()));

                if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) {

                    csrfHeaderPassed = true;
                    logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName);
                    break;
                } else {
                    logger.info(
                            "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName);
                }
            }

        }
        // String csrfCookieVal = (String) session
        // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM);
        // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) {
        // // chain.doFilter(request, response);
        // // return;
        // csrfHeaderPassed = true;
        // } else {
        // // logger.info(reqInfo);
        // // sendSecurityReject(response);
        // }
    }

    if (useCsrfToken && csrfHeaderPassed) {
        chain.doFilter(request, response);
        return;
    }

    // Validate that the salt is in the cache
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache != null) {
        // Get the salt sent with the request
        String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);

        logger.debug("doFilter: csrf saltName=" + saltName);

        if (saltName != null) {

            String salt = httpReq.getParameter(saltName);

            logger.debug("doFilter: csrf salt=" + salt);

            if (salt != null) {

                SecurityInfo si = new SecurityInfo(saltName, salt);

                logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si));

                SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si);
                if (cachedSi != null) {
                    // csrfPreventionSaltCache.invalidate(si);
                    if (SecurityTokenFilter.checkReferer) {
                        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
                        logger.debug("doFilter: refHeader=" + refHeader);
                        if (StringUtils.isNotBlank(refHeader)) {
                            try {
                                URL refUrl = new URL(refHeader);
                                refHeader = refUrl.getHost();
                            } catch (MalformedURLException mex) {
                                logger.debug("doFilter: parsing referer header failed", mex);
                            }
                        }
                        if (!cachedSi.getRefererHost().isEmpty()
                                && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) {
                            logger.info("Potential CSRF detected - Referer host does not match orignal! "
                                    + refHeader + " != " + cachedSi.getRefererHost());
                            sendSecurityReject(response);
                        }
                    }

                    chain.doFilter(request, response);
                } else {
                    logger.info(reqInfo);
                    sendSecurityReject(response);
                }
            } else if (httpMethodMatch(httpReq.getMethod())) {
                // let flow through
                chain.doFilter(request, response);
            } else {
                logger.info(reqInfo);
                sendSecurityReject(response);
            }
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:eu.openanalytics.rsb.component.DataDirectoriesResource.java

@Path("/{rootId}{b64extension : (/b64extension)?}")
@GET//from  ww  w.j a  v a 2s.  c om
public Directory browsePath(@PathParam("rootId") final String rootId,
        @PathParam("b64extension") final String b64extension, @Context final HttpHeaders httpHeaders,
        @Context final UriInfo uriInfo) throws URISyntaxException, IOException {

    final File rootDataDir = rootMap.get(rootId);
    if (rootDataDir == null) {
        throw new NotFoundException(new RuntimeException("No root data dir configured"));
    }

    final String extension = (b64extension != null ? new String(Base64.decodeBase64(b64extension)) : "");
    final File targetDataDir = new File(rootDataDir, extension);

    if (!targetDataDir.exists()) {
        throw new NotFoundException(new RuntimeException("Invalid root data dir: " + targetDataDir));
    }

    // ensure the target data dir is below the root dir to prevent tampering
    final String rootDataDirCanonicalPath = rootDataDir.getCanonicalPath();
    final String targetDataDirCanonicalPath = targetDataDir.getCanonicalPath();
    if (!StringUtils.startsWith(targetDataDirCanonicalPath, rootDataDirCanonicalPath)) {
        throw new AccessDeniedException("Target data dir: " + targetDataDirCanonicalPath
                + " is not below root dir: " + rootDataDirCanonicalPath);
    }

    final Directory result = Util.REST_OBJECT_FACTORY.createDirectory();
    result.setPath(rootDataDirCanonicalPath + extension);
    result.setName(targetDataDir.getName());
    result.setUri(Util.buildDataDirectoryUri(httpHeaders, uriInfo, rootId, b64extension).toString());

    final File[] targetDataDirFiles = targetDataDir.listFiles();
    result.setEmpty(targetDataDirFiles.length == 0);

    for (final File child : targetDataDirFiles) {
        if (FileUtils.isSymlink(child)) {
            getLogger().warn("Symlinks are not supported: " + child);
        } else if (child.isFile()) {
            final FileType fileType = Util.REST_OBJECT_FACTORY.createFileType();
            fileType.setPath(child.getCanonicalPath());
            fileType.setName(child.getName());
            result.getFiles().add(fileType);
        } else if (child.isDirectory()) {
            final Directory childDir = Util.REST_OBJECT_FACTORY.createDirectory();
            childDir.setPath(child.getCanonicalPath());
            childDir.setName(child.getName());
            final String childB64extension = Base64.encodeBase64URLSafeString(
                    StringUtils.difference(rootDataDirCanonicalPath, child.getCanonicalPath()).getBytes());
            childDir.setUri(
                    Util.buildDataDirectoryUri(httpHeaders, uriInfo, rootId, childB64extension).toString());
            childDir.setEmpty(isDirectoryEmpty(child));
            result.getDirectories().add(childDir);
        } else {
            getLogger().warn("Unsupported file type: " + child);
        }
    }

    return result;
}

From source file:de.teamgrit.grit.checking.testing.JavaProjectTester.java

/**
 * Creates the fully qualified name of a class based on its location
 * relative to a base directory./*from   ww w.  j  av  a  2s.c  o  m*/
 *
 * @param basePath
 *            the base path
 * @param subPath
 *            the path to the classfile, must be a located bellow basepath
 *            in the directory tree
 * @return the fully name of the class
 */
private String getQuallifiedName(Path basePath, Path subPath) {
    // relative resolution
    String quallifiedName = StringUtils.difference(basePath.toString(), subPath.toString());
    quallifiedName = quallifiedName.substring(1);
    quallifiedName = FilenameUtils.removeExtension(quallifiedName);
    quallifiedName = StringUtils.replaceChars(quallifiedName, '/', '.');

    return quallifiedName;
}

From source file:info.pancancer.arch3.test.TestWorkerWithMocking.java

@Test
public void testRunWorker()
        throws ShutdownSignalException, ConsumerCancelledException, InterruptedException, Exception {

    PowerMockito.whenNew(DefaultExecuteResultHandler.class).withNoArguments().thenReturn(this.handler);
    Mockito.doAnswer(new Answer<Object>() {
        @Override//from   www.  j  ava2  s. com
        public Object answer(InvocationOnMock invocation) throws Throwable {
            for (int i = 0; i < 5; i++) {
                CommandLine cli = new CommandLine("echo");
                cli.addArgument("iteration: " + i);
                mockExecutor.execute(cli);
                Thread.sleep(500);
            }
            CommandLine cli = new CommandLine("bash");
            cli.addArgument("./src/test/resources/err_output.sh");
            mockExecutor.execute(cli);
            // Here we make sure that the Handler that always gets used always returns 0, and then everything completes OK.
            handler.onProcessComplete(0);
            return null;
        }
    }).when(mockExecutor).execute(any(CommandLine.class), any(ExecuteResultHandler.class));
    PowerMockito.whenNew(DefaultExecutor.class).withNoArguments().thenReturn(mockExecutor);

    setupConfig();

    Job j = new Job();
    j.setWorkflowPath("/workflows/Workflow_Bundle_HelloWorld_1.0-SNAPSHOT_SeqWare_1.1.0");
    j.setWorkflow("HelloWorld");
    j.setWorkflowVersion("1.0-SNAPSHOT");
    j.setJobHash("asdlk2390aso12jvrej");
    j.setUuid("1234567890");
    Map<String, String> iniMap = new HashMap<>(3);
    iniMap.put("param1", "value1");
    iniMap.put("param2", "value2");
    iniMap.put("param3", "help I'm trapped in an INI file");
    j.setIni(iniMap);
    byte[] body = j.toJSON().getBytes();
    Delivery testDelivery = new Delivery(mockEnvelope, mockProperties, body);
    Mockito.when(mockConsumer.nextDelivery()).thenReturn(testDelivery);

    PowerMockito.whenNew(QueueingConsumer.class).withArguments(mockChannel).thenReturn(mockConsumer);

    WorkerRunnable testWorker = new WorkerRunnable("src/test/resources/workerConfig.ini", "vm123456", 1);

    testWorker.run();
    // String testResults = TestWorkerWithMocking.outBuffer.toString();// this.outStream.toString();

    Mockito.verify(mockAppender, Mockito.atLeastOnce()).doAppend(argCaptor.capture());
    List<LoggingEvent> tmpList = new LinkedList<LoggingEvent>(argCaptor.getAllValues());
    String testResults = this.appendEventsIntoString(tmpList);

    testResults = cleanResults(testResults);
    // System.out.println("\n===============================\nTest Results: " + testResults);
    // System.out.println(testResults);
    String expectedDockerCommand = "docker run --rm -h master -t -v /var/run/docker.sock:/var/run/docker.sock -v /workflows/Workflow_Bundle_HelloWorld_1.0-SNAPSHOT_SeqWare_1.1.0:/workflow -v /tmp/seqware_tmpfile.ini:/ini -v /datastore:/datastore -v /home/$USER/.gnos:/home/$USER/.gnos -v /home/$USER/custom-seqware-settings:/home/seqware/.seqware/settings pancancer/seqware_whitestar_pancancer:1.2.3.4 seqware bundle launch --dir /workflow --ini /ini --no-metadata --engine whitestar";
    // System.out.println(expectedDockerCommand);
    assertTrue("Check for docker command, got " + testResults, testResults.contains(expectedDockerCommand));
    assertTrue("Check for sleep message in the following:" + testResults,
            testResults.contains("Sleeping before executing workflow for 1000 ms."));
    assertTrue("Check for workflow complete", testResults.contains("Docker execution result: \"iteration: 0\"\n"
            + "\"iteration: 1\"\n" + "\"iteration: 2\"\n" + "\"iteration: 3\"\n" + "\"iteration: 4\"\n"));

    String begining = new String(Files.readAllBytes(Paths.get("src/test/resources/testResult_Start.txt")));
    assertTrue("check begining of output:" + StringUtils.difference(begining, testResults),
            testResults.contains(begining));

    assertTrue("check INI: " + testResults,
            testResults.contains("param1=value1") && testResults.contains("param2=value2")
                    && testResults.contains("param3=help I'm trapped in an INI file"));

    String ending = new String(Files.readAllBytes(Paths.get("src/test/resources/testResult_End.txt")));
    assertTrue("check ending of output", testResults.contains(ending));

    String initalHeartbeat = new String(
            Files.readAllBytes(Paths.get("src/test/resources/testInitialHeartbeat.txt")));
    assertTrue("Check for an initial heart beat, found" + testResults, testResults.contains(initalHeartbeat));

    assertTrue("check for stderr in heartbeat", testResults.contains("\"stderr\": \"123_err\","));
}

From source file:com.cognifide.qa.bb.aem.touch.siteadmin.aem62.SiteadminPage.java

private void goForwardToDestination(String currentUrl, String destination) {
    ChildPageRow closestPage = getChildPageWindow().getChildPageRows().stream()
            .filter(childPage -> childPage.getHref().equals(destination)).findFirst()
            .orElseGet(() -> getChildPageWindow().getChildPageRows().stream()
                    .collect(Collectors.toMap(Function.identity(),
                            childPageRow -> StringUtils.difference(currentUrl, childPageRow.getHref())))
                    .entrySet().stream().min(Comparator.comparingInt(a -> a.getValue().length())).get()
                    .getKey());/*ww w.ja va 2s  . com*/
    closestPage.click();
}

From source file:me.hurel.hqlbuilder.builder.HQBQueryStringVisitor.java

private String getAliasOrPath(Object entity) {
    String result = null;//from w  w  w . j a va2  s .c o  m
    if (joinedEntities.contains(entity)) {
        result = aliases.get(entity);
    } else if (!parentEntities.containsKey(entity) && entity instanceof String) {
        if (acceptParameters) {
            addParameter(entity);
            result = "?" + (params++);
        } else {
            result = (String) entity;
        }
    }
    if (result == null) {
        Object knownJoinParent = entity;
        while (knownJoinParent != null && !joinedEntities.contains(knownJoinParent)) {
            knownJoinParent = parentEntities.get(knownJoinParent);
        }
        if (!joinedEntities.contains(knownJoinParent)) {
            throw new RuntimeException("Failed to continue query after [" + query.toString()
                    + "] because an entity was used in clause but neither it nor its parent appears explicitly in the from clause");
        }
        if (!aliases.containsKey(knownJoinParent)) {
            throw new RuntimeException("Failed to continue query after [" + query.toString()
                    + "] because alias of the parent joined entity is unknown");
        }
        result = paths.get(entity);
        if (entity != knownJoinParent) {
            String joinedParentPath = paths.get(knownJoinParent);
            String end = StringUtils.difference(joinedParentPath, result);
            result = new StringBuilder(aliases.get(knownJoinParent)).append(end.startsWith(".") ? "" : '.')
                    .append(end).toString();
        }
    }
    return result;
}

From source file:com.cognifide.qa.bb.aem.touch.siteadmin.aem62.SiteadminPage.java

private void goBackUsingNavigator(String destination, String currentUrl) {
    String closestPath = navigatorDropdown.getAvailablePaths().stream().distinct()
            .filter(path -> !currentUrl.equals(path))
            .collect(Collectors.toMap(Function.identity(), path -> StringUtils.difference(path, destination)))
            .entrySet().stream().min(Comparator.comparingInt(a -> a.getValue().length())).get().getKey();
    navigatorDropdown.selectByPath(closestPath);
}