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

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

Introduction

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

Prototype

public static String removeEnd(final String str, final String remove) 

Source Link

Document

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

A null source string will return null .

Usage

From source file:org.wso2.ballerinalang.compiler.BinaryFileWriter.java

private String getOutputFileName(BLangPackage packageNode, String suffix) {
    if (packageNode.packageID.isUnnamed) {
        String sourceFileName = packageNode.packageID.sourceFileName.value;
        if (sourceFileName.endsWith(BLANG_SOURCE_EXT)) {
            sourceFileName = StringUtils.removeEnd(sourceFileName, BLANG_SOURCE_EXT)
                    .concat(BLANG_COMPILED_PROG_EXT);
        }/*  w w w . j ava  2  s .c o  m*/
        return sourceFileName;
    }

    return packageNode.packageID.name.value + suffix;
}

From source file:org.xlrnet.metadict.engines.woxikon.WoxikonEngine.java

private void extractDescription(@NotNull Element element, String queryString,
        DictionaryObjectBuilder objectBuilder) {
    Element descriptionNode = element.getElementsByClass(CLASS_DESCRIPTION).first();
    if (descriptionNode == null) {
        // Try to detect the description node with an alternative class (necessary for synonyms)
        descriptionNode = element.getElementsByClass(CLASS_EXTRA_INFO).first();
    }/* w w  w .j  a va2  s  .  co  m*/
    if (descriptionNode != null) {
        String description = descriptionNode.text();

        description = StringUtils.removeStart(description, DESCRIPTION_BEGIN);
        description = StringUtils.removeEnd(description, DESCRIPTION_END);

        if (!StringUtils.equalsIgnoreCase(description, queryString)) // Set description only if it is different from request string
            objectBuilder.setDescription(StringUtils.strip(description));
    }
}

From source file:org.xwiki.filter.instance.internal.output.XWikiDocumentOutputFilterStream.java

@Override
public void beginWikiClassProperty(String name, String type, FilterEventParameters parameters)
        throws FilterException {
    ComponentManager componentManager = this.componentManagerProvider.get();

    PropertyClassProvider provider;//from w  ww  . jav  a2 s . co  m

    // First try to use the specified class type as hint.
    try {
        if (componentManager.hasComponent(PropertyClassProvider.class, type)) {
            provider = componentManager.getInstance(PropertyClassProvider.class, type);
        } else {
            // In previous versions the class type was the full Java class name of the property class
            // implementation. Extract the hint by removing the Java package prefix and the Class suffix.
            String classType = StringUtils.removeEnd(StringUtils.substringAfterLast(type, "."), "Class");
            provider = componentManager.getInstance(PropertyClassProvider.class, classType);
        }
    } catch (ComponentLookupException e) {
        throw new FilterException(
                String.format("Failed to get instance of the property class provider for type [%s]", type), e);
    }

    this.currentClassPropertyMeta = provider.getDefinition();

    // We should use PropertyClassInterface (instead of PropertyClass, its default implementation) but it
    // doesn't have the set methods and adding them would breaks the backwards compatibility. We make the
    // assumption that all property classes extend PropertyClass.
    this.currentClassProperty = (PropertyClass) provider.getInstance();
    this.currentClassProperty.setName(name);
    this.currentClassProperty.setObject(this.currentXClass);

    this.currentXClass.safeput(name, this.currentClassProperty);
}

From source file:org.xwiki.index.tree.internal.parentchild.DocumentQueryHelper.java

/**
 * Creates a query that returns documents matching the specified constraints.
 * //from w  w w . ja  v  a 2  s  .com
 * @param constraints the document constraints
 * @param parameters the query parameters
 * @param config the tree configuration properties
 * @return the query
 * @throws QueryException if creating the query fails
 */
public Query getQuery(List<String> constraints, Map<String, Object> parameters, Map<String, Object> config)
        throws QueryException {
    String fromClause = "";
    List<String> finalConstraints = new ArrayList<String>();
    Map<String, Object> finalParameters = new HashMap<String, Object>();
    String xclass = (String) config.get("filterByClass");
    if (!StringUtils.isEmpty(xclass)) {
        fromClause = ", BaseObject as obj";
        finalConstraints.add("obj.name = doc.fullName");
        finalConstraints.add("obj.className = :class");
        finalConstraints.add("doc.fullName <> :template");
        finalParameters.put("class", xclass);
        finalParameters.put("template", StringUtils.removeEnd(xclass, "Class") + "Template");
    }
    finalConstraints.addAll(constraints);
    finalParameters.putAll(parameters);
    String whereClause = "where " + StringUtils.join(finalConstraints, " and ");
    String statement = StringUtils
            .join(Arrays.asList(fromClause, whereClause, "order by lower(doc.name), doc.name"), ' ');
    Query query = this.queryManager.createQuery(statement, Query.HQL);
    for (Map.Entry<String, Object> entry : finalParameters.entrySet()) {
        query.bindValue(entry.getKey(), entry.getValue());
    }
    if (Boolean.TRUE.equals(config.get("filterHiddenDocuments"))) {
        query.addFilter(this.hiddenDocumentQueryFilter);
    }
    return query;
}

From source file:org.xwiki.ircbot.internal.wiki.WikiIRCBotListener.java

/**
 * Execute the Wiki bot listener written in wiki syntax by executing the Macros and send the result to the IRC
 * server.//w  ww  .j  av  a2s . c o  m
 *
 * @param event the IRC Bot Event
 */
@Override
public void onEvent(final Event event) {
    // Get the Event class name, remove the "Event" suffix, and prefix with "on". For example for "MessageEvent"
    // this gives "onMessage".
    // Find the XDOM to execute, using this key.
    String eventName = "on" + StringUtils.removeEnd(event.getClass().getSimpleName(), "Event");

    final XDOM xdom = this.events.get(eventName);
    if (xdom != null) {
        LOGGER.debug("Start processing Wiki IRC Bot Listener [{}] for Event [{}], for thread [{}]",
                this.listenerData.getReference(), event, Thread.currentThread());

        // Note that if a Bot Listener script needs access to the IRC Bot (for example to send a message to the
        // IRC channel), it can access it through the "ircbot" Script Service.

        try {
            // Add bindings to the XWiki Context so that the Bot Script Service can access them and thus give access
            // to them to the Bot Listener.
            addBindings(event);

            // Execute the Macro Transformation on XDOM and send the result to the IRC server
            executeAsUser(xdom, event);
        } catch (Exception e) {
            // An error happened, try to send a message to the channel about the error and log a warning.
            try {
                event.respond(String.format("An error occurred while executing Wiki IRC Bot Listener [%s]. "
                        + "Check your server logs.", this.listenerData.getReference()));
            } catch (Exception nestedException) {
                // We tried our best, give up!
            }
            getLogger().warn(String.format("Failed to execute IRC Bot Listener script [%s]", eventName), e);
        }

        LOGGER.debug("Stop processing Wiki IRC Bot Listener [{}] for Event [{}], for thread [{}]",
                this.listenerData.getReference(), event, Thread.currentThread());
    }
}

From source file:org.xwiki.rendering.internal.parser.markdown.AbstractTextPegdownVisitor.java

@Override
public void visit(VerbatimNode verbatimNode) {
    String text = StringUtils.removeEnd(verbatimNode.getText(), "\n");

    Map<String, String> parameters;
    if (verbatimNode.getType().length() > 0) {
        parameters = Collections.singletonMap("language", verbatimNode.getType());
    } else {/*from w w  w  .  ja v  a2 s. c o  m*/
        parameters = Collections.EMPTY_MAP;
    }

    getListener().onMacro(CODE_MACRO_ID, parameters, text, false);
}

From source file:org.xwiki.watchlist.internal.DefaultWatchListEventHTMLDiffExtractor.java

/**
 * @param objectDiffs the list of object diff
 * @param isXWikiClass true if the diff to compute is for an XWiki class, false if it's a plain XWiki object
 * @param documentFullName full name of the document the diff is computed for
 * @param diff the diff plugin API/*from  w  ww .j ava 2s .  c  o  m*/
 * @return the HTML string displaying the specified list of diffs
 */
private String getObjectsHTMLDiff(List<List<ObjectDiff>> objectDiffs, boolean isXWikiClass,
        String documentFullName, DiffPluginApi diff) {
    StringBuffer result = new StringBuffer();
    String propSeparator = ": ";
    String prefix = (isXWikiClass) ? "class" : "object";

    try {
        for (List<ObjectDiff> oList : objectDiffs) {
            if (oList.isEmpty()) {
                continue;
            }

            // The main container
            Div mainDiv = createDiffDiv(prefix + "Diff");

            // Class name
            Span objectName = createDiffSpan(prefix + "ClassName");
            if (isXWikiClass) {
                objectName.addElement(documentFullName);
            } else {
                objectName.addElement(oList.get(0).getClassName());
            }
            mainDiv.addElement(prefix + HTML_IMG_PLACEHOLDER_SUFFIX);
            mainDiv.addElement(objectName);

            // Diffs for each property
            for (ObjectDiff oDiff : oList) {
                String propDiff = getPropertyHTMLDiff(oDiff, diff);
                if (StringUtils.isBlank(oDiff.getPropName()) || StringUtils.isBlank(propDiff)) {
                    // Skip invalid properties or the ones that have no changed.
                    continue;
                }

                Div propDiv = createDiffDiv("propDiffContainer");

                // Property name
                Span propNameSpan = createDiffSpan("propName");
                propNameSpan.addElement(oDiff.getPropName() + propSeparator);
                String shortPropType = StringUtils.removeEnd(oDiff.getPropType(), "Class").toLowerCase();
                if (StringUtils.isBlank(shortPropType)) {
                    // When the diff shows a property that has been deleted, its type is not available.
                    shortPropType = HTML_IMG_METADATA_PREFIX;
                }
                propDiv.addElement(shortPropType + HTML_IMG_PLACEHOLDER_SUFFIX);
                propDiv.addElement(propNameSpan);

                // Property diff
                Div propDiffDiv = createDiffDiv("propDiff");
                propDiffDiv.addElement(propDiff);
                propDiv.addElement(propDiffDiv);

                // Add it to the main div
                mainDiv.addElement(propDiv);
            }

            result.append(mainDiv);
        }
    } catch (XWikiException e) {
        // Catch the exception to be sure we won't send emails containing stacktraces to users.
        logger.error("Failed to compute HTML objects or class diff", e);
    }

    return result.toString();
}

From source file:org.xwiki.wikistream.instance.internal.output.XWikiDocumentOutputWikiStream.java

@Override
public void beginWikiClassProperty(String name, String type, FilterEventParameters parameters)
        throws WikiStreamException {
    ComponentManager componentManager = this.componentManagerProvider.get();

    PropertyClassProvider provider;//  w  ww  .  ja va  2  s.  c  o  m

    // First try to use the specified class type as hint.
    try {
        if (componentManager.hasComponent(PropertyClassProvider.class, type)) {
            provider = componentManager.getInstance(PropertyClassProvider.class, type);
        } else {
            // In previous versions the class type was the full Java class name of the property class
            // implementation. Extract the hint by removing the Java package prefix and the Class suffix.
            String classType = StringUtils.removeEnd(StringUtils.substringAfterLast(type, "."), "Class");
            provider = componentManager.getInstance(PropertyClassProvider.class, classType);
        }
    } catch (ComponentLookupException e) {
        throw new WikiStreamException(
                String.format("Failed to get instance of the property class provider for type [%s]", type), e);
    }

    this.currentClassPropertyMeta = provider.getDefinition();

    // We should use PropertyClassInterface (instead of PropertyClass, its default implementation) but it
    // doesn't have the set methods and adding them would breaks the backwards compatibility. We make the
    // assumption that all property classes extend PropertyClass.
    this.currentClassProperty = (PropertyClass) provider.getInstance();
    this.currentClassProperty.setName(name);
    this.currentClassProperty.setObject(this.currentXClass);

    this.currentXClass.safeput(name, this.currentClassProperty);
}

From source file:org.xwiki.xar.internal.XarObjectPropertySerializerManager.java

/**
 * @param type the property type for which to find a serializer
 * @return the property serializer, if none could be found for the provided type the default one is returned
 * @throws ComponentLookupException when failing to lookup property serializer
 *//*from   w w  w  .  ja  va  2s. c  o m*/
public XarObjectPropertySerializer getPropertySerializer(String type) throws ComponentLookupException {
    if (type != null) {
        ComponentManager componentManager = this.componentManagerProvider.get();

        if (componentManager.hasComponent(XarObjectPropertySerializer.class, type)) {
            // First try to use the specified class type as hint.
            return getInstance(type, componentManager);
        } else {
            // In previous versions the class type was the full Java class name of the property class
            // implementation. Extract the hint by removing the Java package prefix and the Class suffix.
            String simpleType = StringUtils.removeEnd(StringUtils.substringAfterLast(type, "."), "Class");

            if (componentManager.hasComponent(XarObjectPropertySerializer.class, simpleType)) {
                return getInstance(simpleType, componentManager);
            }
        }
    }

    return this.defaultPropertySerializer;
}

From source file:org.yamj.core.service.artwork.ArtworkProcessorService.java

private void generateImage(ArtworkLocated located, ArtworkProfile profile) throws Exception {
    StorageType storageType;/* w ww .ja v  a2  s .c  o  m*/
    if (located.getArtwork().getArtworkType() == ArtworkType.PHOTO) {
        storageType = StorageType.PHOTO;
    } else {
        storageType = StorageType.ARTWORK;
    }

    LOG.debug("Generate image for {} with profile {}", located, profile.getProfileName());
    BufferedImage imageGraphic = null;
    try {
        imageGraphic = GraphicTools
                .loadJPEGImage(this.fileStorageService.getFile(storageType, located.getCacheFilename()));
    } catch (OutOfMemoryError ex) {
        LOG.error("Failed to load/transform image '{}' due to memory constraints", located.getCacheFilename());
    }

    if (imageGraphic == null) {
        LOG.error("Error processing image '{}', not processed further.", located.getCacheFilename());
        // Mark the image as unprocessable
        located.setStatus(StatusType.ERROR);
        artworkStorageService.updateArtworkLocated(located);
        // quit
        return;
    }

    // set dimension of original image if not done before
    if (located.getWidth() <= 0 || located.getHeight() <= 0) {
        located.setWidth(imageGraphic.getWidth());
        located.setHeight(imageGraphic.getHeight());
    }

    // draw the image
    BufferedImage image = drawImage(imageGraphic, profile);

    // store image on stage system
    String cacheFilename = buildCacheFilename(located, profile);
    fileStorageService.storeImage(cacheFilename, storageType, image, profile.getImageFormat(),
            profile.getQuality());

    try {
        ArtworkGenerated generated = new ArtworkGenerated();
        generated.setArtworkLocated(located);
        generated.setArtworkProfile(profile);
        generated.setCacheFilename(cacheFilename);
        String cacheDirectory = FileTools.createDirHash(cacheFilename);
        generated.setCacheDirectory(StringUtils.removeEnd(cacheDirectory, File.separator + cacheFilename));
        artworkStorageService.storeArtworkGenerated(generated);
    } catch (Exception ex) {
        // delete generated file storage element also
        LOG.trace("Failed to generate file storage for {}, error: {}", cacheFilename, ex.getMessage());
        try {
            fileStorageService.delete(storageType, cacheFilename);
        } catch (IOException ex2) {
            LOG.trace("Unable to delete file after exception: {}", ex2.getMessage(), ex);
        }
        throw ex;
    }
}