Example usage for org.apache.commons.lang StringUtils strip

List of usage examples for org.apache.commons.lang StringUtils strip

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils strip.

Prototype

public static String strip(String str, String stripChars) 

Source Link

Document

Strips any of a set of characters from the start and end of a String.

Usage

From source file:org.cloudifysource.dsl.utils.IPUtils.java

/**
 * Returns a "safe" formatted IP address - IPv4 addresses are not changed,
 * IPv6 addresses may change - if they include an "interface" section it is removed,
 * and the address itself is surrounded by brackets ("[]") to allow for port concatenation. 
 * @param ipAddress The ipAddress to handle
 * @return an IP address, "safe" for concatenation.
 *//*  w w  w.  j av  a 2  s.  c o  m*/
public static String getSafeIpAddress(final String ipAddress) {

    String safeIpAddress;
    try {
        String strippedIp = StringUtils.strip(ipAddress, "[]");
        strippedIp = StringUtils.substringBefore(strippedIp, NETWORK_INTERFACE_SEPARATOR);
        IPv6Address.fromString(strippedIp); //verifies this is an IPv6 address
        safeIpAddress = "[" + strippedIp + "]";
    } catch (IllegalArgumentException e) {
        //this is not a valid IPv6 address, assume this is IPv4 or host name, leave as is
        safeIpAddress = ipAddress;
    }

    return safeIpAddress;
}

From source file:org.codehaus.mojo.mrm.impl.maven.DiskArtifactStore.java

/**
 * {@inheritDoc}//  w  w w . jav a 2  s. co  m
 */
public Metadata getMetadata(String path) throws IOException, MetadataNotFoundException {
    File file = root;
    String[] parts = StringUtils.strip(path, "/").split("/");
    for (int i = 0; i < parts.length; i++) {
        file = new File(file, parts[i]);
    }
    file = new File(file, "maven-metadata.xml");
    if (!file.isFile()) {
        throw new MetadataNotFoundException(path);
    }
    MetadataXpp3Reader reader = new MetadataXpp3Reader();
    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream(file);
        return reader.read(inputStream);
    } catch (XmlPullParserException e) {
        IOException ioe = new IOException(e.getMessage());
        ioe.initCause(e);
        throw ioe;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.codehaus.mojo.mrm.impl.maven.DiskArtifactStore.java

/**
 * {@inheritDoc}//w ww  . j a  va  2s .co m
 */
public long getMetadataLastModified(String path) throws IOException, MetadataNotFoundException {
    File file = root;
    String[] parts = StringUtils.strip(path, "/").split("/");
    Stack<File> stack = new Stack<File>();
    for (int i = 0; i < parts.length; i++) {
        if ("..".equals(parts[i])) {
            if (!stack.isEmpty()) {
                file = (File) stack.pop();
            } else {
                file = root;
            }
        } else if (!".".equals(parts[i])) {
            file = new File(file, parts[i]);
            stack.push(file);
        }
    }
    file = new File(file, "maven-metadata.xml");
    if (!file.isFile()) {
        throw new MetadataNotFoundException(path);
    }
    return file.lastModified();
}

From source file:org.codehaus.mojo.mrm.impl.maven.FileSystemArtifactStore.java

/**
 * {@inheritDoc}// w w  w  .j a  v  a2  s  . c o  m
 */
public Metadata getMetadata(String path) throws IOException, MetadataNotFoundException {
    Entry entry = backing.get(StringUtils.join(StringUtils.split(StringUtils.strip(path, "/"), "/"), "/")
            + "/maven-metadata.xml");
    if (!(entry instanceof FileEntry)) {
        throw new MetadataNotFoundException(path);
    }
    MetadataXpp3Reader reader = new MetadataXpp3Reader();
    InputStream inputStream = null;
    try {
        inputStream = ((FileEntry) entry).getInputStream();
        return reader.read(inputStream);
    } catch (XmlPullParserException e) {
        IOException ioe = new IOException(e.getMessage());
        ioe.initCause(e);
        throw ioe;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.codehaus.mojo.mrm.impl.maven.FileSystemArtifactStore.java

/**
 * {@inheritDoc}/*from  ww  w.  j  a v  a2 s  .  c  om*/
 */
public long getMetadataLastModified(String path) throws IOException, MetadataNotFoundException {
    Entry entry = backing.get(StringUtils.join(StringUtils.split(StringUtils.strip(path, "/"), "/"), "/")
            + "/maven-metadata.xml");
    if (!(entry instanceof FileEntry)) {
        throw new MetadataNotFoundException(path);
    }
    return entry.getLastModified();
}

From source file:org.codice.ddf.commands.solr.BackupCommand.java

private String getBackupUrl(String coreName) {
    String backupUrl = SolrClientFactory.getDefaultHttpsAddress();

    if (configurationAdmin != null) {
        try {/*from   w  w  w.ja  v a  2 s  .co  m*/
            Configuration solrConfig = configurationAdmin
                    .getConfiguration("(service.pid=ddf.catalog.solr.external.SolrHttpCatalogProvider)");
            if (solrConfig != null) {
                if (solrConfig.getProperties() != null && solrConfig.getProperties().get("url") != null) {
                    LOGGER.debug("Found url property in config, setting backup url");
                    backupUrl = (String) solrConfig.getProperties().get("url");
                } else {
                    LOGGER.info("No Solr config found, checking System settings");
                    if (System.getProperty("host") != null && System.getProperty("jetty.port") != null
                            && System.getProperty("hostContext") != null) {
                        backupUrl = System.getProperty("urlScheme", "http") + "://" + System.getProperty("host")
                                + ":" + System.getProperty("jetty.port") + "/"
                                + StringUtils.strip(System.getProperty("hostContext"), "/");
                        LOGGER.info("Trying system configured URL instead: {}", backupUrl);
                    } else {
                        LOGGER.info("No Solr url configured, defaulting to: {}",
                                SolrClientFactory.getDefaultHttpsAddress());
                    }
                }
            }
        } catch (IOException e) {
            LOGGER.debug("Unable to get Solr url from bundle config, will check system properties.");
        }
    }
    return backupUrl + "/" + coreName + "/replication";
}

From source file:org.commonjava.indy.core.content.MavenMetadataGenerator.java

@Override
public List<StoreResource> generateDirectoryContent(final ArtifactStore store, final String path,
        final List<StoreResource> existing, final EventMetadata eventMetadata) throws IndyWorkflowException {
    final StoreResource mdResource = new StoreResource(LocationUtils.toLocation(store),
            Paths.get(path, MavenMetadataMerger.METADATA_NAME).toString());

    if (existing.contains(mdResource)) {
        return null;
    }//from ww w.j  a  v  a  2s  .co  m

    int pathElementsCount = StringUtils.strip(path, "/").split("/").length;
    // if there is a possibility we are listing an artifactId
    if (pathElementsCount >= 2) {
        // regardless, we will need this first level of listings. What we do with it will depend on the logic below...
        final List<StoreResource> firstLevelFiles = fileManager.listRaw(store, path);

        ArtifactPathInfo samplePomInfo = null;
        nextTopResource: for (final StoreResource topResource : firstLevelFiles) {
            final String topPath = topResource.getPath();
            if (topPath.endsWith(".pom")) {
                samplePomInfo = ArtifactPathInfo.parse(topPath);
                break;
            } else if (topPath.endsWith("/")) {
                final List<StoreResource> secondLevelListing = fileManager.listRaw(store, topPath);
                for (final StoreResource fileResource : secondLevelListing) {
                    if (fileResource.getPath().endsWith(".pom")) {
                        if (samplePomInfo == null) {
                            samplePomInfo = ArtifactPathInfo.parse(fileResource.getPath());
                            break nextTopResource;
                        }

                        continue nextTopResource;
                    }
                }
            }
        }

        // TODO: Generation of plugin metadata files (groupId-level) is harder, and requires cracking open the jar file
        // This is because that's the only place the plugin prefix can be reliably retrieved from.
        // We won't worry about this for now.
        if (samplePomInfo != null) {
            final List<StoreResource> result = new ArrayList<StoreResource>();
            result.add(mdResource);
            result.add(new StoreResource(LocationUtils.toLocation(store),
                    Paths.get(path, MavenMetadataMerger.METADATA_MD5_NAME).toString()));
            result.add(new StoreResource(LocationUtils.toLocation(store),
                    Paths.get(path, MavenMetadataMerger.METADATA_SHA_NAME).toString()));
            return result;
        }
    }

    return null;
}

From source file:org.commonjava.indy.pkg.maven.content.MavenMetadataGenerator.java

@Override
public List<StoreResource> generateDirectoryContent(final ArtifactStore store, final String path,
        final List<StoreResource> existing, final EventMetadata eventMetadata) throws IndyWorkflowException {
    final StoreResource mdResource = new StoreResource(LocationUtils.toLocation(store),
            Paths.get(path, MavenMetadataMerger.METADATA_NAME).toString());

    if (existing.contains(mdResource)) {
        return null;
    }//w  w w.j  a  v  a 2  s.co  m

    int pathElementsCount = StringUtils.strip(path, "/").split("/").length;
    // if there is a possibility we are listing an artifactId
    if (pathElementsCount >= 2) {
        // regardless, we will need this first level of listings. What we do with it will depend on the logic below...
        final List<StoreResource> firstLevelFiles = fileManager.listRaw(store, path, eventMetadata);

        ArtifactPathInfo samplePomInfo = null;
        for (final StoreResource topResource : firstLevelFiles) {
            final String topPath = topResource.getPath();
            if (topPath.endsWith(".pom")) {
                samplePomInfo = ArtifactPathInfo.parse(topPath);
                break;
            }
        }

        // if this dir does not contain a pom check if a subdir contain a pom
        if (samplePomInfo == null) {
            List<String> firstLevelDirs = firstLevelFiles.stream().map((res) -> res.getPath())
                    .filter((subpath) -> subpath.endsWith("/")).collect(Collectors.toList());
            final Map<String, List<StoreResource>> secondLevelMap = fileManager.listRaw(store, firstLevelDirs,
                    eventMetadata);
            nextTopResource: for (final String topPath : firstLevelDirs) {
                final List<StoreResource> secondLevelListing = secondLevelMap.get(topPath);
                for (final StoreResource fileResource : secondLevelListing) {
                    if (fileResource.getPath().endsWith(".pom")) {
                        if (samplePomInfo == null) {
                            samplePomInfo = ArtifactPathInfo.parse(fileResource.getPath());
                            break nextTopResource;
                        }

                        continue nextTopResource;
                    }
                }
            }
        }

        // TODO: Generation of plugin metadata files (groupId-level) is harder, and requires cracking open the jar file
        // This is because that's the only place the plugin prefix can be reliably retrieved from.
        // We won't worry about this for now.
        if (samplePomInfo != null) {
            final List<StoreResource> result = new ArrayList<>();
            result.add(mdResource);
            result.add(new StoreResource(LocationUtils.toLocation(store),
                    Paths.get(path, MavenMetadataMerger.METADATA_MD5_NAME).toString()));
            result.add(new StoreResource(LocationUtils.toLocation(store),
                    Paths.get(path, MavenMetadataMerger.METADATA_SHA_NAME).toString()));
            return result;
        }
    }

    return null;
}

From source file:org.datacleaner.cli.GrouperIT.java

private void checkOutputFileForInconsistencies(final String filePath) {
    try {//from  www  .  ja  va 2 s.c  o m
        final List<String> lines = Files.readLines(new File(filePath), Charsets.UTF_8);

        for (int i = 1; i < lines.size(); i++) { // skipping header
            final String[] values = lines.get(i).split(";");
            final int grouperCount = Integer.parseInt(StringUtils.strip(values[0], "\""));
            final String[] idList = values[1].split(",");
            final int expectedCount = EXPECTED_GROUP_LENGTHS[i - 1];

            if (grouperCount != idList.length || grouperCount != expectedCount) {
                fail(String.format("Size inconsistency at line: %d (%d != %d || %d != %d)", i, grouperCount,
                        idList.length, grouperCount, expectedCount));
            }
        }
    } catch (IOException e) {
        fail(e.getMessage());
    }
}

From source file:org.eclipse.skalli.view.internal.filter.ProjectDetailsFilter.java

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

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    String userId = (String) request.getAttribute(Consts.ATTRIBUTE_USERID);
    Project project = (Project) request.getAttribute(Consts.ATTRIBUTE_PROJECT);
    boolean isProjectAdmin = BooleanUtils
            .toBoolean((Boolean) request.getAttribute(Consts.ATTRIBUTE_PROJECTADMIN));
    boolean isProjectAdminInParentChain = BooleanUtils
            .toBoolean((Boolean) request.getAttribute(Consts.ATTRIBUTE_PARENTPROJECTADMIN));
    String action = request.getParameter(Consts.PARAM_ACTION);

    String windowName = StringUtils.strip(httpRequest.getPathInfo(), "/"); //$NON-NLS-1$
    if (project != null) {
        if (!project.isDeleted()) {
            windowName = project.getProjectId();
        } else {/*w  w w .  j a  v a2 s.c  o m*/
            windowName = project.getUuid().toString();
        }

        ProjectTemplateService templateService = Services.getRequiredService(ProjectTemplateService.class);
        ProjectTemplate projectTemplate = templateService
                .getProjectTemplateById(project.getProjectTemplateId());
        request.setAttribute(Consts.ATTRIBUTE_PROJECTTEMPLATE, projectTemplate);
        request.setAttribute(Consts.ATTRIBUTE_NATURE, projectTemplate.getProjectNature().toString());

        if (userId != null) {
            FavoritesService favoritesService = Services.getService(FavoritesService.class);
            Favorites favorites = null;
            if (favoritesService == null) {
                favorites = new Favorites(userId);
            } else {
                favorites = favoritesService.getFavorites(userId);
            }
            request.setAttribute(Consts.ATTRIBUTE_FAVORITES, favorites.asMap());

            boolean showIssues = isProjectAdmin || isProjectAdminInParentChain;
            request.setAttribute(Consts.ATTRIBUTE_SHOW_ISSUES, isProjectAdmin);

            if (showIssues) {
                IssuesService issuesService = Services.getService(IssuesService.class);
                if (issuesService != null) {
                    if (Consts.PARAM_VALUE_VALIDATE.equals(action)) {
                        ValidationService validationService = Services.getService(ValidationService.class);
                        if (validationService != null) {
                            validationService.validate(Project.class, project.getUuid(), Severity.INFO, userId);
                        }
                    }
                    Issues issues = issuesService.getByUUID(project.getUuid());
                    if (issues != null && issues.hasIssues()) {
                        request.setAttribute(Consts.ATTRIBUTE_ISSUES, issues);
                        request.setAttribute(Consts.ATTRIBUTE_MAX_SEVERITY,
                                issues.getIssues().first().getSeverity().name());
                    }
                }
            }

            request.setAttribute(Consts.ATTRIBUTE_PROJECTCONTEXTLINKS,
                    getOrderedVisibleProjectContextLinks(project, userId));
        }

        String pathInfo = httpRequest.getPathInfo();
        if (pathInfo != null) {
            int infoBoxIndex = pathInfo.indexOf(Consts.URL_INFOBOXES);
            if (infoBoxIndex > 0) {
                if (StringUtils.isNotBlank(action)) {
                    String infoBoxShortName = pathInfo.substring(infoBoxIndex + Consts.URL_INFOBOXES.length());
                    if (infoBoxShortName.startsWith(FilterUtil.PATH_SEPARATOR)) {
                        infoBoxShortName = infoBoxShortName.substring(1);
                    }
                    filterInfobox(project, infoBoxShortName, action, userId);
                }
            }
        }
    }
    request.setAttribute(Consts.ATTRIBUTE_WINDOWNAME, windowName);
    request.setAttribute(Consts.ATTRIBUTE_EDITMODE, false);

    String appUri = Consts.URL_VAADIN_PROJECTS + windowName;
    if (StringUtils.isNotBlank(action)) {
        if (action.equals(Consts.PARAM_VALUE_EDIT)) {
            request.setAttribute(Consts.ATTRIBUTE_EDITMODE, true);
            appUri = appUri + "/edit"; //$NON-NLS-1$
        }
    }
    request.setAttribute(Consts.ATTRIBUTE_APP_URI, appUri);

    // proceed along the chain
    chain.doFilter(request, response);
}