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

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

Introduction

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

Prototype

public static String removeEnd(String str, String remove) 

Source Link

Document

Removes a substring only if it is at the end of a source string, otherwise returns the source string.

Usage

From source file:org.cesecore.certificates.ca.catoken.CAToken.java

/**
 * Use current key sequence to generate and store a "next" key sequence and "next" singing key alias.
 * @return the next sign key alias./*from w ww. j a  v a2s. c o  m*/
 */
public String generateNextSignKeyAlias() {
    // Generate a new key sequence
    final String currentKeySequence = getKeySequence();
    final String newKeySequence = StringTools.incrementKeySequence(getKeySequenceFormat(), currentKeySequence);
    if (log.isDebugEnabled()) {
        log.debug("Current key sequence: " + currentKeySequence + "  New key sequence: " + newKeySequence);
    }
    // Generate a key alias based on the new key sequence
    final String currentCertSignKeyLabel = keyStrings.getAlias(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
    final String newCertSignKeyLabel = StringUtils.removeEnd(currentCertSignKeyLabel, currentKeySequence)
            + newKeySequence;
    if (log.isDebugEnabled()) {
        log.debug("Current sign key alias: " + currentCertSignKeyLabel + "  New sign key alias: "
                + newCertSignKeyLabel);
    }
    // Store the new values in the properties of this token
    setNextCertSignKey(newCertSignKeyLabel);
    setNextKeySequence(newKeySequence);
    return newCertSignKeyLabel;
}

From source file:org.codehaus.mojo.mrm.impl.digest.AutoDigestFileSystem.java

/**
 * {@inheritDoc}//from w  ww.j a  va 2  s . co  m
 */
public Entry get(String path) {
    Entry entry = backing.get(path);
    if (entry == null) {
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        if (path.length() == 0) {
            return getRoot();
        }
        String[] parts = path.split("/");
        if (parts.length == 0) {
            return getRoot();
        }
        DirectoryEntry parent = getRoot();
        for (int i = 0; i < parts.length - 1; i++) {
            parent = new DefaultDirectoryEntry(this, parent, parts[i]);
        }
        String name = parts[parts.length - 1];
        for (DigestFileEntryFactory factory : digestFactories.values()) {
            if (name.endsWith(factory.getType())) {
                Entry shadow = backing
                        .get(parent.toPath() + "/" + StringUtils.removeEnd(name, factory.getType()));
                return factory.create(this, parent, (FileEntry) shadow);
            }
        }
        return get(parent, name);
    } else {
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        if (path.length() == 0) {
            return getRoot();
        }
        String[] parts = path.split("/");
        if (parts.length == 0) {
            return getRoot();
        }
        DirectoryEntry parent = getRoot();
        for (int i = 0; i < parts.length - 1; i++) {
            parent = new DefaultDirectoryEntry(this, parent, parts[i]);
        }
        if (entry instanceof FileEntry) {
            // repair filesystems that lie to us because they are caching
            for (DigestFileEntryFactory factory : digestFactories.values()) {
                if (entry.getName().endsWith(factory.getType())) {
                    Entry shadow = backing.get(
                            parent.toPath() + "/" + StringUtils.removeEnd(entry.getName(), factory.getType()));
                    return new GenerateOnErrorFileEntry(this, parent, (FileEntry) entry,
                            factory.create(this, parent, (FileEntry) shadow));
                }
            }
            return new LinkFileEntry(this, parent, (FileEntry) entry);
        } else if (entry instanceof DirectoryEntry) {
            for (DigestFileEntryFactory factory : digestFactories.values()) {
                if (entry.getName().endsWith(factory.getType())) {
                    Entry shadow = backing.get(
                            parent.toPath() + "/" + StringUtils.removeEnd(entry.getName(), factory.getType()));
                    return factory.create(this, parent, (FileEntry) shadow);
                }
            }
            return new DefaultDirectoryEntry(this, parent, entry.getName());
        }
    }
    return null;
}

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

/**
 * {@inheritDoc}/*from   w  ww  .j a v  a2  s .c o  m*/
 */
protected Entry get(DirectoryEntry parent, String name) {

    String path = parent.toPath() + "/" + name;

    if ("favicon.ico".equals(name)) {
        return null;
    }
    if (METADATA.matcher(path).matches()) {
        MetadataFileEntry entry = new MetadataFileEntry(this, parent, parent.toPath(), store);
        try {
            entry.getLastModified();
            return entry;
        } catch (IOException e) {
            return null;
        }
    } else {
        Matcher snapshotArtifact = SNAPSHOT_ARTIFACT.matcher(path);
        if (snapshotArtifact.matches()) {
            String groupId = StringUtils.stripEnd(snapshotArtifact.group(1), "/").replace('/', '.');
            String artifactId = snapshotArtifact.group(2);
            String version = snapshotArtifact.group(3) + "-SNAPSHOT";
            Pattern rule = Pattern.compile("\\Q" + artifactId + "\\E-(?:\\Q"
                    + StringUtils.removeEnd(version, "-SNAPSHOT")
                    + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?\\.([^/]*)");
            Matcher matcher = rule.matcher(name);
            if (!matcher.matches()) {
                String classifier = snapshotArtifact.group(5);
                String type = snapshotArtifact.group(6);
                if (classifier != null) {
                    classifier = classifier.substring(1);
                }
                if (StringUtils.isEmpty(classifier)) {
                    classifier = null;
                }
                return new ArtifactFileEntry(this, parent,
                        new Artifact(groupId, artifactId, version, classifier, type), store);
            }
            if (matcher.group(1).equals("SNAPSHOT")) {
                Artifact artifact = new Artifact(groupId, artifactId, version, matcher.group(9),
                        matcher.group(10));
                try {
                    store.get(artifact);
                    return new ArtifactFileEntry(this, parent, artifact, store);
                } catch (IOException e) {
                    return null;
                } catch (ArtifactNotFoundException e) {
                    return null;
                }
            }
            try {
                Calendar cal = new GregorianCalendar();
                cal.setTimeZone(TimeZone.getTimeZone("GMT"));
                cal.set(Calendar.YEAR, Integer.parseInt(matcher.group(2)));
                cal.set(Calendar.MONTH, Integer.parseInt(matcher.group(3)) - 1);
                cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(4)));
                cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(matcher.group(5)));
                cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(6)));
                cal.set(Calendar.SECOND, Integer.parseInt(matcher.group(7)));
                long timestamp = cal.getTimeInMillis();
                int buildNumber = Integer.parseInt(matcher.group(8));

                Artifact artifact = new Artifact(groupId, artifactId, version, matcher.group(9),
                        matcher.group(10), timestamp, buildNumber);
                try {
                    store.get(artifact);
                    return new ArtifactFileEntry(this, parent, artifact, store);
                } catch (IOException e) {
                    return null;
                } catch (ArtifactNotFoundException e) {
                    return null;
                }
            } catch (NullPointerException e) {
                return new DefaultDirectoryEntry(this, parent, name);
            }
        } else {
            Matcher matcher = ARTIFACT.matcher(path);
            if (matcher.matches()) {
                String groupId = StringUtils.stripEnd(matcher.group(1), "/").replace('/', '.');
                String artifactId = matcher.group(2);
                String version = matcher.group(3);
                String classifier = matcher.group(5);
                String type = matcher.group(6);
                if (classifier != null) {
                    classifier = classifier.substring(1);
                }
                if (StringUtils.isEmpty(classifier)) {
                    classifier = null;
                }

                Artifact artifact = new Artifact(groupId, artifactId, version, classifier, type);
                try {
                    store.get(artifact);
                    return new ArtifactFileEntry(this, parent, artifact, store);
                } catch (ArtifactNotFoundException e) {
                    return null;
                } catch (IOException e) {
                    return null;
                }
            } else {
                return new DefaultDirectoryEntry(this, parent, name);
            }
        }
    }
}

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

/**
 * {@inheritDoc}//from   ww w . j  a  va2 s .co  m
 */
public Set<Artifact> getArtifacts(final String groupId, final String artifactId, final String version) {
    File groupDir = new File(root, groupId.replace('.', '/'));
    File artifactDir = new File(groupDir, artifactId);
    File versionDir = new File(artifactDir, version);
    if (!versionDir.isDirectory()) {
        return Collections.emptySet();
    }
    final Pattern rule;

    abstract class ArtifactFactory {
        abstract Artifact get(File file);
    }

    final ArtifactFactory factory;
    if (version.endsWith("-SNAPSHOT")) {
        rule = Pattern.compile("\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd(version, "-SNAPSHOT")
                + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?\\.([^/]*)");
        factory = new ArtifactFactory() {
            public Artifact get(File file) {
                Matcher matcher = rule.matcher(file.getName());
                if (!matcher.matches()) {
                    return null;
                }
                if (matcher.group(1).equals("SNAPSHOT")) {
                    return new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10));
                }
                try {
                    Calendar cal = new GregorianCalendar();
                    cal.setTimeZone(TimeZone.getTimeZone("GMT"));
                    cal.set(Calendar.YEAR, Integer.parseInt(matcher.group(2)));
                    cal.set(Calendar.MONTH, Integer.parseInt(matcher.group(3)) - 1);
                    cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(4)));
                    cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(matcher.group(5)));
                    cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(6)));
                    cal.set(Calendar.SECOND, Integer.parseInt(matcher.group(7)));
                    long timestamp = cal.getTimeInMillis();
                    int buildNumber = Integer.parseInt(matcher.group(8));
                    return new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10),
                            timestamp, buildNumber);
                } catch (NullPointerException e) {
                    return null;
                }
            }
        };
    } else {
        rule = Pattern.compile("\\Q" + artifactId + "\\E-\\Q" + version + "\\E(?:-([^.]+))?\\.(.+)");
        factory = new ArtifactFactory() {
            public Artifact get(File file) {
                Matcher matcher = rule.matcher(file.getName());
                if (!matcher.matches()) {
                    return null;
                }
                return new Artifact(groupId, artifactId, version, matcher.group(1), matcher.group(2));
            }
        };
    }
    File[] files = versionDir.listFiles();
    Set<Artifact> result = new HashSet<Artifact>(files.length);
    for (int i = 0; i < files.length; i++) {
        if (!files[i].isFile() || !rule.matcher(files[i].getName()).matches()) {
            continue;
        }
        Artifact artifact = factory.get(files[i]);
        if (artifact != null) {
            result.add(artifact);
        }
    }
    return result;
}

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

/**
 * {@inheritDoc}/*from w  ww . j  a  va2  s .c om*/
 */
public Set<Artifact> getArtifacts(final String groupId, final String artifactId, final String version) {
    Entry parentEntry = backing.get(groupId.replace('.', '/') + "/" + artifactId + "/" + version);
    if (!(parentEntry instanceof DirectoryEntry)) {
        return Collections.emptySet();
    }
    DirectoryEntry parentDir = (DirectoryEntry) parentEntry;
    Entry[] entries = backing.listEntries(parentDir);
    final Pattern rule;

    abstract class ArtifactFactory {
        abstract Artifact get(Entry entry);
    }

    final ArtifactFactory factory;
    if (version.endsWith("-SNAPSHOT")) {
        rule = Pattern.compile("\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd(version, "-SNAPSHOT")
                + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?\\.([^/]*)");
        factory = new ArtifactFactory() {
            public Artifact get(Entry entry) {
                Matcher matcher = rule.matcher(entry.getName());
                if (!matcher.matches()) {
                    return null;
                }
                if (matcher.group(1).equals("SNAPSHOT")) {
                    return new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10));
                }
                try {
                    Calendar cal = new GregorianCalendar();
                    cal.setTimeZone(TimeZone.getTimeZone("GMT"));
                    cal.set(Calendar.YEAR, Integer.parseInt(matcher.group(2)));
                    cal.set(Calendar.MONTH, Integer.parseInt(matcher.group(3)) - 1);
                    cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(4)));
                    cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(matcher.group(5)));
                    cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(6)));
                    cal.set(Calendar.SECOND, Integer.parseInt(matcher.group(7)));
                    long timestamp = cal.getTimeInMillis();
                    int buildNumber = Integer.parseInt(matcher.group(8));
                    return new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10),
                            timestamp, buildNumber);
                } catch (NullPointerException e) {
                    return null;
                }
            }
        };
    } else {
        rule = Pattern.compile("\\Q" + artifactId + "\\E-\\Q" + version + "\\E(?:-([^.]+))?\\.(.+)");
        factory = new ArtifactFactory() {
            public Artifact get(Entry entry) {
                Matcher matcher = rule.matcher(entry.getName());
                if (!matcher.matches()) {
                    return null;
                }
                return new Artifact(groupId, artifactId, version, matcher.group(1), matcher.group(2));
            }
        };
    }
    Set<Artifact> result = new HashSet<Artifact>(entries.length);
    for (int i = 0; i < entries.length; i++) {
        if (!(entries[i] instanceof FileEntry) || !rule.matcher(entries[i].getName()).matches()) {
            continue;
        }
        Artifact artifact = factory.get(entries[i]);
        if (artifact != null) {
            result.add(artifact);
        }
    }
    return result;
}

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

/**
 * {@inheritDoc}/*  w  w w.j  a va  2  s  .c o  m*/
 */
public synchronized Metadata getMetadata(String path) throws IOException, MetadataNotFoundException {
    Metadata metadata = new Metadata();
    boolean foundMetadata = false;
    path = StringUtils.stripEnd(StringUtils.stripStart(path, "/"), "/");
    String groupId = path.replace('/', '.');
    Set pluginArtifactIds = getArtifactIds(groupId);
    if (pluginArtifactIds != null) {
        List plugins = new ArrayList();
        for (Iterator i = pluginArtifactIds.iterator(); i.hasNext();) {
            String artifactId = (String) i.next();
            Set pluginVersions = getVersions(groupId, artifactId);
            if (pluginVersions == null || pluginVersions.isEmpty()) {
                continue;
            }
            String[] versions = (String[]) pluginVersions.toArray(new String[pluginVersions.size()]);
            Arrays.sort(versions, new VersionComparator());
            MavenXpp3Reader reader = new MavenXpp3Reader();
            for (int j = versions.length - 1; j >= 0; j--) {
                InputStream inputStream = null;
                try {
                    inputStream = get(new Artifact(groupId, artifactId, versions[j], "pom"));
                    Model model = reader.read(new XmlStreamReader(inputStream));
                    if (model == null || !"maven-plugin".equals(model.getPackaging())) {
                        continue;
                    }
                    Plugin plugin = new Plugin();
                    plugin.setArtifactId(artifactId);
                    plugin.setName(model.getName());
                    // TODO proper goal-prefix determination
                    // ugh! this is incredibly hacky and does not handle some fool that sets the goal prefix in
                    // a parent pom... ok unlikely, but stupid is as stupid does
                    boolean havePrefix = false;
                    final Build build = model.getBuild();
                    if (build != null && build.getPlugins() != null) {
                        havePrefix = setPluginGoalPrefixFromConfiguration(plugin, build.getPlugins());
                    }
                    if (!havePrefix && build != null && build.getPluginManagement() != null
                            && build.getPluginManagement().getPlugins() != null) {
                        havePrefix = setPluginGoalPrefixFromConfiguration(plugin,
                                build.getPluginManagement().getPlugins());
                    }
                    if (!havePrefix && artifactId.startsWith("maven-") && artifactId.endsWith("-plugin")) {
                        plugin.setPrefix(StringUtils.removeStart(StringUtils.removeEnd(artifactId, "-plugin"),
                                "maven-"));
                        havePrefix = true;
                    }
                    if (!havePrefix && artifactId.endsWith("-maven-plugin")) {
                        plugin.setPrefix(StringUtils.removeEnd(artifactId, "-maven-plugin"));
                        havePrefix = true;
                    }
                    if (!havePrefix) {
                        plugin.setPrefix(artifactId);
                    }
                    plugins.add(plugin);
                    foundMetadata = true;
                    break;
                } catch (ArtifactNotFoundException e) {
                    // ignore
                } catch (XmlPullParserException e) {
                    // ignore
                } finally {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        }
        if (!plugins.isEmpty()) {
            metadata.setPlugins(plugins);
        }
    }
    int index = path.lastIndexOf('/');
    groupId = (index == -1 ? groupId : groupId.substring(0, index)).replace('/', '.');
    String artifactId = (index == -1 ? null : path.substring(index + 1));
    if (artifactId != null) {
        Set artifactVersions = getVersions(groupId, artifactId);
        if (artifactVersions != null && !artifactVersions.isEmpty()) {
            metadata.setGroupId(groupId);
            metadata.setArtifactId(artifactId);
            Versioning versioning = new Versioning();
            List versions = new ArrayList(artifactVersions);
            Collections.sort(versions, new VersionComparator()); // sort the Maven way
            long lastUpdated = 0;
            for (Iterator i = versions.iterator(); i.hasNext();) {
                String version = (String) i.next();
                try {
                    long lastModified = getLastModified(new Artifact(groupId, artifactId, version, "pom"));
                    versioning.addVersion(version);
                    if (lastModified >= lastUpdated) {
                        lastUpdated = lastModified;
                        versioning.setLastUpdatedTimestamp(new Date(lastModified));
                        versioning.setLatest(version);
                        if (!version.endsWith("-SNAPSHOT")) {
                            versioning.setRelease(version);
                        }
                    }
                } catch (ArtifactNotFoundException e) {
                    // ignore
                }
            }
            metadata.setVersioning(versioning);
            foundMetadata = true;
        }
    }

    int index2 = index == -1 ? -1 : path.lastIndexOf('/', index - 1);
    groupId = index2 == -1 ? groupId : groupId.substring(0, index2).replace('/', '.');
    artifactId = index2 == -1 ? artifactId : path.substring(index2 + 1, index);
    String version = index2 == -1 ? null : path.substring(index + 1);
    if (version != null && version.endsWith("-SNAPSHOT")) {
        Map artifactMap = (Map) contents.get(groupId);
        Map versionMap = (Map) (artifactMap == null ? null : artifactMap.get(artifactId));
        Map filesMap = (Map) (versionMap == null ? null : versionMap.get(version));
        if (filesMap != null) {
            List snapshotVersions = new ArrayList();
            int maxBuildNumber = 0;
            long lastUpdated = 0;
            String timestamp = null;
            boolean found = false;
            for (Iterator i = filesMap.entrySet().iterator(); i.hasNext();) {
                final Map.Entry entry = (Map.Entry) i.next();
                final Artifact artifact = (Artifact) entry.getKey();
                final Content content = (Content) entry.getValue();
                SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
                fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
                String lastUpdatedTime = fmt.format(new Date(content.getLastModified()));
                try {
                    Maven3.addSnapshotVersion(snapshotVersions, artifact, lastUpdatedTime);
                } catch (LinkageError e) {
                    // Maven 2
                }
                if ("pom".equals(artifact.getType())) {
                    if (artifact.getBuildNumber() != null
                            && maxBuildNumber < artifact.getBuildNumber().intValue()) {
                        maxBuildNumber = artifact.getBuildNumber().intValue();
                        timestamp = artifact.getTimestampString();
                    } else {
                        maxBuildNumber = Math.max(1, maxBuildNumber);
                    }
                    lastUpdated = Math.max(lastUpdated, content.getLastModified());
                    found = true;
                }
            }

            if (!snapshotVersions.isEmpty() || found) {
                Versioning versioning = metadata.getVersioning();
                if (versioning == null) {
                    versioning = new Versioning();
                }
                metadata.setGroupId(groupId);
                metadata.setArtifactId(artifactId);
                metadata.setVersion(version);
                try {
                    Maven3.addSnapshotVersions(versioning, snapshotVersions);
                } catch (LinkageError e) {
                    // Maven 2
                }
                if (maxBuildNumber > 0) {
                    Snapshot snapshot = new Snapshot();
                    snapshot.setBuildNumber(maxBuildNumber);
                    snapshot.setTimestamp(timestamp);
                    versioning.setSnapshot(snapshot);
                }
                versioning.setLastUpdatedTimestamp(new Date(lastUpdated));
                metadata.setVersioning(versioning);
                foundMetadata = true;
            }
        }

    }
    if (!foundMetadata) {
        throw new MetadataNotFoundException(path);
    }
    return metadata;
}

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

/**
 * {@inheritDoc}/*  w  ww  .  j av  a 2 s.co  m*/
 */
public synchronized Metadata getMetadata(String path) throws IOException, MetadataNotFoundException {
    Metadata metadata = new Metadata();
    boolean foundMetadata = false;
    path = StringUtils.stripEnd(StringUtils.stripStart(path, "/"), "/");
    String groupId = path.replace('/', '.');
    Set<String> pluginArtifactIds = getArtifactIds(groupId);
    if (pluginArtifactIds != null) {
        List<Plugin> plugins = new ArrayList<Plugin>();
        for (String artifactId : pluginArtifactIds) {
            Set<String> pluginVersions = getVersions(groupId, artifactId);
            if (pluginVersions == null || pluginVersions.isEmpty()) {
                continue;
            }
            String[] versions = pluginVersions.toArray(new String[pluginVersions.size()]);
            Arrays.sort(versions, new VersionComparator());
            MavenXpp3Reader reader = new MavenXpp3Reader();
            for (int j = versions.length - 1; j >= 0; j--) {
                InputStream inputStream = null;
                try {
                    inputStream = get(new Artifact(groupId, artifactId, versions[j], "pom"));
                    Model model = reader.read(new XmlStreamReader(inputStream));
                    if (model == null || !"maven-plugin".equals(model.getPackaging())) {
                        continue;
                    }
                    Plugin plugin = new Plugin();
                    plugin.setArtifactId(artifactId);
                    plugin.setName(model.getName());
                    // TODO proper goal-prefix determination
                    // ugh! this is incredibly hacky and does not handle some fool that sets the goal prefix in
                    // a parent pom... ok unlikely, but stupid is as stupid does
                    boolean havePrefix = false;
                    final Build build = model.getBuild();
                    if (build != null && build.getPlugins() != null) {
                        havePrefix = setPluginGoalPrefixFromConfiguration(plugin, build.getPlugins());
                    }
                    if (!havePrefix && build != null && build.getPluginManagement() != null
                            && build.getPluginManagement().getPlugins() != null) {
                        havePrefix = setPluginGoalPrefixFromConfiguration(plugin,
                                build.getPluginManagement().getPlugins());
                    }
                    if (!havePrefix && artifactId.startsWith("maven-") && artifactId.endsWith("-plugin")) {
                        plugin.setPrefix(StringUtils.removeStart(StringUtils.removeEnd(artifactId, "-plugin"),
                                "maven-"));
                        havePrefix = true;
                    }
                    if (!havePrefix && artifactId.endsWith("-maven-plugin")) {
                        plugin.setPrefix(StringUtils.removeEnd(artifactId, "-maven-plugin"));
                        havePrefix = true;
                    }
                    if (!havePrefix) {
                        plugin.setPrefix(artifactId);
                    }
                    plugins.add(plugin);
                    foundMetadata = true;
                    break;
                } catch (ArtifactNotFoundException e) {
                    // ignore
                } catch (XmlPullParserException e) {
                    // ignore
                } finally {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        }
        if (!plugins.isEmpty()) {
            metadata.setPlugins(plugins);
        }
    }
    int index = path.lastIndexOf('/');
    groupId = (index == -1 ? groupId : groupId.substring(0, index)).replace('/', '.');
    String artifactId = (index == -1 ? null : path.substring(index + 1));
    if (artifactId != null) {
        Set<String> artifactVersions = getVersions(groupId, artifactId);
        if (artifactVersions != null && !artifactVersions.isEmpty()) {
            metadata.setGroupId(groupId);
            metadata.setArtifactId(artifactId);
            Versioning versioning = new Versioning();
            List<String> versions = new ArrayList<String>(artifactVersions);
            Collections.sort(versions, new VersionComparator()); // sort the Maven way
            long lastUpdated = 0;
            for (String version : versions) {
                try {
                    long lastModified = getLastModified(new Artifact(groupId, artifactId, version, "pom"));
                    versioning.addVersion(version);
                    if (lastModified >= lastUpdated) {
                        lastUpdated = lastModified;
                        versioning.setLastUpdatedTimestamp(new Date(lastModified));
                        versioning.setLatest(version);
                        if (!version.endsWith("-SNAPSHOT")) {
                            versioning.setRelease(version);
                        }
                    }
                } catch (ArtifactNotFoundException e) {
                    // ignore
                }
            }
            metadata.setVersioning(versioning);
            foundMetadata = true;
        }
    }

    int index2 = index == -1 ? -1 : path.lastIndexOf('/', index - 1);
    groupId = index2 == -1 ? groupId : groupId.substring(0, index2).replace('/', '.');
    artifactId = index2 == -1 ? artifactId : path.substring(index2 + 1, index);
    String version = index2 == -1 ? null : path.substring(index + 1);
    if (version != null && version.endsWith("-SNAPSHOT")) {
        Map<String, Map<String, Map<Artifact, Content>>> artifactMap = contents.get(groupId);
        Map<String, Map<Artifact, Content>> versionMap = (artifactMap == null ? null
                : artifactMap.get(artifactId));
        Map<Artifact, Content> filesMap = (versionMap == null ? null : versionMap.get(version));
        if (filesMap != null) {
            List<SnapshotVersion> snapshotVersions = new ArrayList<SnapshotVersion>();
            int maxBuildNumber = 0;
            long lastUpdated = 0;
            String timestamp = null;
            boolean found = false;
            for (final Map.Entry<Artifact, Content> entry : filesMap.entrySet()) {
                final Artifact artifact = entry.getKey();
                final Content content = entry.getValue();
                SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
                fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
                String lastUpdatedTime = fmt.format(new Date(content.getLastModified()));
                try {
                    Maven3.addSnapshotVersion(snapshotVersions, artifact, lastUpdatedTime);
                } catch (LinkageError e) {
                    // Maven 2
                }
                if ("pom".equals(artifact.getType())) {
                    if (artifact.getBuildNumber() != null
                            && maxBuildNumber < artifact.getBuildNumber().intValue()) {
                        maxBuildNumber = artifact.getBuildNumber().intValue();
                        timestamp = artifact.getTimestampString();
                    } else {
                        maxBuildNumber = Math.max(1, maxBuildNumber);
                    }
                    lastUpdated = Math.max(lastUpdated, content.getLastModified());
                    found = true;
                }
            }

            if (!snapshotVersions.isEmpty() || found) {
                Versioning versioning = metadata.getVersioning();
                if (versioning == null) {
                    versioning = new Versioning();
                }
                metadata.setGroupId(groupId);
                metadata.setArtifactId(artifactId);
                metadata.setVersion(version);
                try {
                    Maven3.addSnapshotVersions(versioning, snapshotVersions);
                } catch (LinkageError e) {
                    // Maven 2
                }
                if (maxBuildNumber > 0) {
                    Snapshot snapshot = new Snapshot();
                    snapshot.setBuildNumber(maxBuildNumber);
                    snapshot.setTimestamp(timestamp);
                    versioning.setSnapshot(snapshot);
                }
                versioning.setLastUpdatedTimestamp(new Date(lastUpdated));
                metadata.setVersioning(versioning);
                foundMetadata = true;
            }
        }

    }
    if (!foundMetadata) {
        throw new MetadataNotFoundException(path);
    }
    return metadata;
}

From source file:org.codehaus.mojo.taglist.FileAnalyser.java

/**
 * Scans a file to look for task tags./*ww w  .  ja v  a 2  s  . c om*/
 * 
 * @param file the file to scan.
 */
public void scanFile(File file) {
    LineNumberReader reader = null;

    try {
        reader = new LineNumberReader(getReader(file));

        String currentLine = reader.readLine();
        while (currentLine != null) {
            int index = -1;
            Iterator iter = tagClasses.iterator();
            // look for a tag on this line
            while (iter.hasNext()) {
                TagClass tagClass = (TagClass) iter.next();
                index = tagClass.tagMatchContains(currentLine, locale);
                if (index != TagClass.NO_MATCH) {
                    // there's a tag on this line
                    String commentType = null;
                    commentType = extractCommentType(currentLine, index);

                    if (commentType == null) {
                        // this is not a valid comment tag: skip other tag classes and
                        // go to the next line
                        break;
                    }

                    int tagLength = tagClass.getLastTagMatchStringLength();
                    int commentStartIndex = reader.getLineNumber();
                    StringBuffer comment = new StringBuffer();

                    String firstLine = StringUtils.strip(currentLine.substring(index + tagLength));
                    firstLine = StringUtils.removeEnd(firstLine, "*/"); //MTAGLIST-35
                    if (firstLine.length() == 0 || ":".equals(firstLine)) {
                        // this is not a valid comment tag: nothing is written there
                        if (emptyCommentsOn) {
                            comment.append("--");
                            comment.append(noCommentString);
                            comment.append("--");
                        } else {
                            continue;
                        }
                    } else {
                        // this tag has a comment
                        if (firstLine.charAt(0) == ':') {
                            comment.append(firstLine.substring(1).trim());
                        } else {
                            comment.append(firstLine);
                        }

                        if (multipleLineCommentsOn) {
                            // Mark the current position, set the read forward limit to
                            // a large number that should not be met.
                            reader.mark(MAX_COMMENT_CHARACTERS);

                            // next line
                            String futureLine = reader.readLine();

                            // we're looking for multiple line comments
                            while (futureLine != null && futureLine.trim().startsWith(commentType)
                                    && futureLine.indexOf(tagClass.getLastTagMatchString()) < 0) {
                                String currentComment = futureLine
                                        .substring(futureLine.indexOf(commentType) + commentType.length())
                                        .trim();
                                if (currentComment.startsWith("@") || "".equals(currentComment)
                                        || "/".equals(currentComment)) {
                                    // the comment is finished
                                    break;
                                }
                                // try to look if the next line is not a new tag
                                boolean newTagFound = false;
                                Iterator moreTCiter = tagClasses.iterator();
                                while (moreTCiter.hasNext()) {
                                    TagClass tc = (TagClass) moreTCiter.next();
                                    if (tc.tagMatchStartsWith(currentComment, locale)) {
                                        newTagFound = true;
                                        break;
                                    }
                                }
                                if (newTagFound) {
                                    // this is a new comment: stop here the current comment
                                    break;
                                }
                                // nothing was found: this means the comment is going on this line
                                comment.append(" ");
                                comment.append(currentComment);
                                futureLine = reader.readLine();
                            }

                            // Reset the reader to the marked position before the multi
                            // line check was performed.
                            reader.reset();
                        }
                    }
                    TagReport tagReport = tagClass.getTagReport();
                    FileReport fileReport = tagReport.getFileReport(file, encoding);
                    fileReport.addComment(comment.toString(), commentStartIndex);
                }
            }
            currentLine = reader.readLine();
        }
    } catch (IOException e) {
        log.error("Error while scanning the file " + file.getPath(), e);
    } finally {
        IOUtil.close(reader);
    }
}

From source file:org.codice.ddf.admin.core.impl.ConfigurationAdminImpl.java

public ConfigurationStatus enableManagedServiceFactoryConfiguration(String servicePid,
        Configuration disabledConfig) throws IOException {
    Dictionary<String, Object> properties = disabledConfig.getProperties();
    String disabledFactoryPid = (String) properties
            .get(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID);
    if (disabledFactoryPid == null) {
        throw new IOException("Configuration does not belong to a managed service factory.");
    }//from  ww w .ja v  a  2 s  .  c om
    if (!StringUtils.endsWith(disabledFactoryPid, ConfigurationStatus.DISABLED_EXTENSION)) {
        throw new IOException("Configuration is already enabled.");
    }

    String enabledFactoryPid = StringUtils.removeEnd(disabledFactoryPid,
            ConfigurationStatus.DISABLED_EXTENSION);
    Dictionary<String, Object> enabledProperties = copyConfigProperties(properties, enabledFactoryPid);
    enabledProperties.put(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID, enabledFactoryPid);
    Configuration enabledConfiguration = configurationAdmin.createFactoryConfiguration(enabledFactoryPid, null);
    enabledConfiguration.update(enabledProperties);

    disabledConfig.delete();

    return new ConfigurationStatusImpl(enabledFactoryPid, enabledConfiguration.getPid(), disabledFactoryPid,
            servicePid);
}

From source file:org.codice.ddf.migration.MigrationException.java

@SuppressWarnings("PMD.DefaultPackage" /* designed to be called from MigrationWarning and MigrationInformation within this package */)
static Object[] sanitizeThrowables(Object[] args) {
    if ((args == null) || (args.length == 0)) {
        return args;
    }// w  w  w .jav a  2 s .c o  m
    final Object[] sargs = new Object[args.length];

    System.arraycopy(args, 0, sargs, 0, args.length);
    for (int i = 0; i < sargs.length; i++) {
        if (sargs[i] instanceof Throwable) {
            // make sure the message doesn't end with a period
            sargs[i] = StringUtils.removeEnd(((Throwable) sargs[i]).getMessage(), ".");
        }
    }
    return sargs;
}