Example usage for org.springframework.util StringUtils arrayToDelimitedString

List of usage examples for org.springframework.util StringUtils arrayToDelimitedString

Introduction

In this page you can find the example usage for org.springframework.util StringUtils arrayToDelimitedString.

Prototype

public static String arrayToDelimitedString(@Nullable Object[] arr, String delim) 

Source Link

Document

Convert a String array into a delimited String (e.g.

Usage

From source file:ch.rasc.wampspring.security.WampMessageSecurityMetadataSourceRegistry.java

private static String hasAnyAuthority(String... authorities) {
    String anyAuthorities = StringUtils.arrayToDelimitedString(authorities, "','");
    return "hasAnyAuthority('" + anyAuthorities + "')";
}

From source file:fr.xebia.servlet.filter.ExpiresFilterTest.java

protected void validate(HttpServlet servlet, Integer expectedMaxAgeInSeconds, int expectedResponseStatusCode)
        throws Exception {
    // SETUP/*  ww w. j  a  v  a2 s  .  c om*/
    int port = 6666;
    Server server = new Server(port);
    Context context = new Context(server, "/", Context.SESSIONS);

    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.addInitParameter("ExpiresDefault", "access plus 1 minute");
    filterConfig.addInitParameter("ExpiresByType text/xml; charset=utf-8", "access plus 3 minutes");
    filterConfig.addInitParameter("ExpiresByType text/xml", "access plus 5 minutes");
    filterConfig.addInitParameter("ExpiresByType text", "access plus 7 minutes");
    filterConfig.addInitParameter("ExpiresExcludedResponseStatusCodes", "304, 503");

    ExpiresFilter expiresFilter = new ExpiresFilter();
    expiresFilter.init(filterConfig);

    context.addFilter(new FilterHolder(expiresFilter), "/*", Handler.REQUEST);

    context.addServlet(new ServletHolder(servlet), "/test");

    server.start();
    try {
        Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        long timeBeforeInMillis = System.currentTimeMillis();

        // TEST
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test")
                .openConnection();

        // VALIDATE
        Assert.assertEquals(expectedResponseStatusCode, httpURLConnection.getResponseCode());

        for (Entry<String, List<String>> field : httpURLConnection.getHeaderFields().entrySet()) {
            System.out.println(field.getKey() + ": "
                    + StringUtils.arrayToDelimitedString(field.getValue().toArray(), ", "));
        }

        Integer actualMaxAgeInSeconds;

        String cacheControlHeader = httpURLConnection.getHeaderField("Cache-Control");
        if (cacheControlHeader == null) {
            actualMaxAgeInSeconds = null;
        } else {
            actualMaxAgeInSeconds = null;
            // System.out.println("Evaluate Cache-Control:" +
            // cacheControlHeader);
            StringTokenizer cacheControlTokenizer = new StringTokenizer(cacheControlHeader, ",");
            while (cacheControlTokenizer.hasMoreTokens() && actualMaxAgeInSeconds == null) {
                String cacheDirective = cacheControlTokenizer.nextToken();
                // System.out.println("\tEvaluate directive: " +
                // cacheDirective);
                StringTokenizer cacheDirectiveTokenizer = new StringTokenizer(cacheDirective, "=");
                // System.out.println("countTokens=" +
                // cacheDirectiveTokenizer.countTokens());
                if (cacheDirectiveTokenizer.countTokens() == 2) {
                    String key = cacheDirectiveTokenizer.nextToken().trim();
                    String value = cacheDirectiveTokenizer.nextToken().trim();
                    if (key.equalsIgnoreCase("max-age")) {
                        actualMaxAgeInSeconds = Integer.parseInt(value);
                    }
                }
            }
        }

        if (expectedMaxAgeInSeconds == null) {
            Assert.assertNull("actualMaxAgeInSeconds '" + actualMaxAgeInSeconds + "' should be null",
                    actualMaxAgeInSeconds);
            return;
        }

        Assert.assertNotNull(actualMaxAgeInSeconds);

        int deltaInSeconds = Math.abs(actualMaxAgeInSeconds - expectedMaxAgeInSeconds);
        Assert.assertTrue("actualMaxAgeInSeconds: " + actualMaxAgeInSeconds + ", expectedMaxAgeInSeconds: "
                + expectedMaxAgeInSeconds + ", request time: " + timeBeforeInMillis + " for content type "
                + httpURLConnection.getContentType(), deltaInSeconds < 2000);

    } finally {
        server.stop();
    }
}

From source file:org.opennms.netmgt.rrd.rrd4j.RRD4JRrdStrategyTest.java

@Test
public void testPrintThroughInterface() throws Exception {
    long end = System.currentTimeMillis();
    long start = end - (24 * 60 * 60 * 1000);
    String[] command = new String[] { "--start=" + start, "--end=" + end, "CDEF:something=1",
            "PRINT:something:AVERAGE:\"%le\"" };

    RrdGraphDetails graphDetails = m_strategy
            .createGraphReturnDetails(StringUtils.arrayToDelimitedString(command, " "), new File(""));
    assertNotNull("graph details object", graphDetails);

    String[] printLines = graphDetails.getPrintLines();
    assertNotNull("graph printLines", printLines);
    assertEquals("graph printLines size", 1, printLines.length);
    assertEquals("graph printLines item 0", "\"1.000000e+00\"", printLines[0]);
}

From source file:net.sf.juffrou.reflect.spring.BeanWrapperTests.java

@Test
public void testStringPropertyWithCustomEditor() throws Exception {
    TestBean tb = new TestBean();
    BeanWrapper bw = new JuffrouSpringBeanWrapper(tb);
    bw.registerCustomEditor(String.class, "name", new PropertyEditorSupport() {
        @Override//from   w  w  w.  j  a va  2s.  c o  m
        public void setValue(Object value) {
            if (value instanceof String[]) {
                setValue(StringUtils.arrayToDelimitedString(((String[]) value), "-"));
            } else {
                super.setValue(value != null ? value : "");
            }
        }
    });
    bw.setPropertyValue("name", new String[] {});
    assertEquals("", tb.getName());
    bw.setPropertyValue("name", new String[] { "a1", "b2" });
    assertEquals("a1-b2", tb.getName());
    bw.setPropertyValue("name", null);
    assertEquals("", tb.getName());
}

From source file:org.opennms.ng.dao.support.PropertiesGraphDao.java

/** {@inheritDoc} */
@Override//from w ww .  j a v a 2 s.  c  o  m
public PrefabGraph[] getPrefabGraphsForResource(OnmsResource resource) {
    if (resource == null) {
        LOG.warn("returning empty graph list for resource because it is null");
        return new PrefabGraph[0];
    }
    Set<OnmsAttribute> attributes = resource.getAttributes();
    // Check if there are no attributes
    if (attributes.size() == 0) {
        LOG.debug("returning empty graph list for resource {} because its attribute list is empty", resource);
        return new PrefabGraph[0];
    }

    Set<String> availableRrdAttributes = resource.getRrdGraphAttributes().keySet();
    Set<String> availableStringAttributes = resource.getStringPropertyAttributes().keySet();
    Set<String> availableExternalAttributes = resource.getExternalValueAttributes().keySet();

    // Check if there are no RRD attributes
    if (availableRrdAttributes.size() == 0) {
        LOG.debug("returning empty graph list for resource {} because it has no RRD attributes", resource);
        return new PrefabGraph[0];
    }

    String resourceType = resource.getResourceType().getName();

    Map<String, PrefabGraph> returnList = new LinkedHashMap<String, PrefabGraph>();
    for (PrefabGraph query : getAllPrefabGraphs()) {
        if (resourceType != null && !query.hasMatchingType(resourceType)) {
            LOG.debug("skipping {} because its types \"{}\" does not match resourceType \"{}\"",
                    query.getName(), StringUtils.arrayToDelimitedString(query.getTypes(), ", "), resourceType);
            continue;
        }

        if (!verifyAttributesExist(query, "RRD", Arrays.asList(query.getColumns()), availableRrdAttributes)) {
            continue;
        }
        if (!verifyAttributesExist(query, "string property", Arrays.asList(query.getPropertiesValues()),
                availableStringAttributes)) {
            continue;
        }
        if (!verifyAttributesExist(query, "external value", Arrays.asList(query.getExternalValues()),
                availableExternalAttributes)) {
            continue;
        }

        LOG.debug("adding {} to query list", query.getName());

        returnList.put(query.getName(), query);
    }

    if (LOG.isDebugEnabled()) {
        ArrayList<String> nameList = new ArrayList<String>(returnList.size());
        for (PrefabGraph graph : returnList.values()) {
            nameList.add(graph.getName());
        }
        LOG.debug("found {} prefabricated graphs for resource {}: {}", nameList.size(), resource,
                StringUtils.collectionToDelimitedString(nameList, ", "));
    }

    Set<String> suppressReports = new HashSet<String>();
    for (Entry<String, PrefabGraph> entry : returnList.entrySet()) {
        suppressReports.addAll(Arrays.asList(entry.getValue().getSuppress()));
    }

    suppressReports.retainAll(returnList.keySet());
    if (suppressReports.size() > 0) {
        LOG.debug("suppressing {} prefabricated graphs for resource {}: {}", suppressReports.size(), resource,
                StringUtils.collectionToDelimitedString(suppressReports, ", "));
    }

    for (String suppressReport : suppressReports) {
        returnList.remove(suppressReport);
    }

    return returnList.values().toArray(new PrefabGraph[returnList.size()]);
}

From source file:org.cloudfoundry.identity.uaa.scim.JdbcScimUserProvisioning.java

@Override
public List<ScimUser> retrieveUsers(String filter, String sortBy, boolean ascending) {
    String where = filter;//from ww w  .  ja v a  2  s .c o  m

    // Single quotes for literals
    where = where.replaceAll("\"", "'");

    if (unquotedEq.matcher(where).matches()) {
        throw new IllegalArgumentException("Eq argument in filter (" + filter + ") must be quoted");
    }

    if (sortBy != null) {
        // Need to add "asc" or "desc" explicitly to ensure that the pattern splitting below works
        where = where + " order by " + sortBy + (ascending ? " asc" : " desc");
    }

    // There is only one email address for now...
    where = StringUtils.arrayToDelimitedString(emailsValuePattern.split(where), "email");
    // There is only one phone number for now...
    where = StringUtils.arrayToDelimitedString(phoneNumbersValuePattern.split(where), "phoneNumber");

    Map<String, Object> values = new HashMap<String, Object>();

    where = makeCaseInsensitive(where, coPattern, "%slower(%s) like :?%s", "%%%s%%", values);
    where = makeCaseInsensitive(where, swPattern, "%slower(%s) like :?%s", "%s%%", values);
    where = makeCaseInsensitive(where, eqPattern, "%slower(%s) = :?%s", "%s", values);
    where = makeBooleans(where, boPattern, "%s%s = :?%s", values);
    where = prPattern.matcher(where).replaceAll(" is not null$1");
    where = gtPattern.matcher(where).replaceAll(" > ");
    where = gePattern.matcher(where).replaceAll(" >= ");
    where = ltPattern.matcher(where).replaceAll(" < ");
    where = lePattern.matcher(where).replaceAll(" <= ");
    // This will catch equality of number literals
    where = where.replaceAll(" eq ", " = ");
    where = makeTimestamps(where, metaPattern, "%s%s %s :?%s", values);
    where = where.replaceAll("meta\\.", "");

    logger.debug("Filtering users with SQL: [" + where + "], and parameters: " + values);

    if (where.contains("emails.")) {
        throw new UnsupportedOperationException(
                "Filters on email address fields other than 'value' not supported");
    }

    if (where.contains("phoneNumbers.")) {
        throw new UnsupportedOperationException(
                "Filters on phone number fields other than 'value' not supported");
    }

    try {
        // Default order is by created date descending
        String order = sortBy == null ? " ORDER BY created desc" : "";
        return new JdbcPagingList<ScimUser>(jdbcTemplate, ALL_USERS + " WHERE " + where + order, values, mapper,
                200);
    } catch (DataAccessException e) {
        logger.debug("Filter '" + filter + "' generated invalid SQL", e);
        throw new IllegalArgumentException("Invalid filter: " + filter);
    }
}

From source file:org.georchestra.security.HeadersManagementStrategy.java

private String sanitizeLocation(HttpServletRequest request, String location, Map<String, String> targets) {
    if (location.startsWith("/")) {
        String[] requestPath = StringUtils.split(location.substring(1), "/");
        if (logger.isDebugEnabled()) {
            if (requestPath.length > 0)
                logger.debug("Sanitize location: " + requestPath[0]);
        }//from   w ww.java  2 s.  c  om
        if (requestPath.length > 0 && targets.containsKey(requestPath[0])) {
            requestPath[0] = targets.get(requestPath[0]);
            return StringUtils.arrayToDelimitedString(requestPath, "/");
        }
    }

    return location;
}

From source file:org.opennms.core.test.db.TemporaryDatabase.java

protected File findIpLikeLibrary() {
    File topDir = ConfigurationTestUtils.getTopProjectDirectory();

    File ipLikeDir = new File(topDir, "opennms-iplike");
    assertTrue("iplike directory exists at ../opennms-iplike: " + ipLikeDir.getAbsolutePath(),
            ipLikeDir.exists());//from  ww  w  .  j a  va  2  s. co m

    File[] ipLikePlatformDirs = ipLikeDir.listFiles(new FileFilter() {
        public boolean accept(File file) {
            if (file.getName().matches("opennms-iplike-.*") && file.isDirectory()) {
                return true;
            } else {
                return false;
            }
        }
    });
    assertTrue(
            "expecting at least one opennms iplike platform directory in " + ipLikeDir.getAbsolutePath()
                    + "; got: " + StringUtils.arrayToDelimitedString(ipLikePlatformDirs, ", "),
            ipLikePlatformDirs.length > 0);

    File ipLikeFile = null;
    for (File ipLikePlatformDir : ipLikePlatformDirs) {
        assertTrue("iplike platform directory does not exist but was listed in directory listing: "
                + ipLikePlatformDir.getAbsolutePath(), ipLikePlatformDir.exists());

        File ipLikeTargetDir = new File(ipLikePlatformDir, "target");
        if (!ipLikeTargetDir.exists() || !ipLikeTargetDir.isDirectory()) {
            // Skip this one
            continue;
        }

        File[] ipLikeFiles = ipLikeTargetDir.listFiles(new FileFilter() {
            public boolean accept(File file) {
                if (file.isFile() && file.getName().matches("opennms-iplike-.*\\.(so|dylib)")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        assertFalse("expecting zero or one iplike file in " + ipLikeTargetDir.getAbsolutePath() + "; got: "
                + StringUtils.arrayToDelimitedString(ipLikeFiles, ", "), ipLikeFiles.length > 1);

        if (ipLikeFiles.length == 1) {
            ipLikeFile = ipLikeFiles[0];
        }

    }

    assertNotNull("Could not find iplike shared object in a target directory in any of these directories: "
            + StringUtils.arrayToDelimitedString(ipLikePlatformDirs, ", "), ipLikeFile);

    return ipLikeFile;
}

From source file:org.opennms.core.test.db.TemporaryDatabasePostgreSQL.java

protected File findIpLikeLibrary() {
    File topDir = ConfigurationTestUtils.getTopProjectDirectory();

    File ipLikeDir = new File(topDir, "opennms-iplike");
    assertTrue("iplike directory exists at ../opennms-iplike: " + ipLikeDir.getAbsolutePath(),
            ipLikeDir.exists());//from ww  w  . jav a2 s. c om

    File[] ipLikePlatformDirs = ipLikeDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.getName().matches("opennms-iplike-.*") && file.isDirectory()) {
                return true;
            } else {
                return false;
            }
        }
    });
    assertTrue(
            "expecting at least one opennms iplike platform directory in " + ipLikeDir.getAbsolutePath()
                    + "; got: " + StringUtils.arrayToDelimitedString(ipLikePlatformDirs, ", "),
            ipLikePlatformDirs.length > 0);

    File ipLikeFile = null;
    for (File ipLikePlatformDir : ipLikePlatformDirs) {
        assertTrue("iplike platform directory does not exist but was listed in directory listing: "
                + ipLikePlatformDir.getAbsolutePath(), ipLikePlatformDir.exists());

        File ipLikeTargetDir = new File(ipLikePlatformDir, "target");
        if (!ipLikeTargetDir.exists() || !ipLikeTargetDir.isDirectory()) {
            // Skip this one
            continue;
        }

        File[] ipLikeFiles = ipLikeTargetDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                if (file.isFile() && file.getName().matches("opennms-iplike-.*\\.(so|dylib)")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        assertFalse("expecting zero or one iplike file in " + ipLikeTargetDir.getAbsolutePath() + "; got: "
                + StringUtils.arrayToDelimitedString(ipLikeFiles, ", "), ipLikeFiles.length > 1);

        if (ipLikeFiles.length == 1) {
            ipLikeFile = ipLikeFiles[0];
        }

    }

    assertNotNull("Could not find iplike shared object in a target directory in any of these directories: "
            + StringUtils.arrayToDelimitedString(ipLikePlatformDirs, ", "), ipLikeFile);

    return ipLikeFile;
}

From source file:org.opennms.install.Installer.java

/**
 * <p>removeFile</p>//from w w  w  .ja va 2  s .  c  o m
 *
 * @param destination a {@link java.lang.String} object.
 * @param description a {@link java.lang.String} object.
 * @param recursive a boolean.
 * @throws java.io.IOException if any.
 * @throws java.lang.InterruptedException if any.
 * @throws java.lang.Exception if any.
 */
public void removeFile(String destination, String description, boolean recursive)
        throws IOException, InterruptedException, Exception {
    String[] cmd;
    ProcessExec e = new ProcessExec(System.out, System.out);

    if (recursive) {
        cmd = new String[3];
        cmd[0] = "rm";
        cmd[1] = "-r";
        cmd[2] = destination;
    } else {
        cmd = new String[2];
        cmd[0] = "rm";
        cmd[1] = destination;
    }
    if (e.exec(cmd) != 0) {
        throw new Exception("Non-zero exit value returned while " + "removing " + description + ", "
                + destination + ", using \"" + StringUtils.arrayToDelimitedString(cmd, " ") + "\"");
    }

    if (new File(destination).exists()) {
        usage(options, m_commandLine, "Could not delete existing " + description + ": " + destination, null);
        System.exit(1);
    }
}