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.ednovo.gooru.domain.service.resource.ResourceServiceImpl.java

private String cleanTitle(String title) {
    final List<String> stringsToRemoveList = Arrays.asList("bbc", "ks2", "read", "phet", "bitesize", "maths");
    Set stringsToRemoveSet = new HashSet<String>(stringsToRemoveList);

    while (true) {
        title = StringUtils.trim(title);
        title = StringUtils.removeStart(title, ",");
        title = StringUtils.removeStart(title, ".");
        title = StringUtils.removeStart(title, "-");
        title = StringUtils.removeStart(title, ":");
        title = StringUtils.removeEnd(title, ",");
        title = StringUtils.removeEnd(title, ".");
        title = StringUtils.removeEnd(title, "-");
        title = StringUtils.removeEnd(title, ":");
        title = StringUtils.trim(title);

        String[] words = StringUtils.split(title, ": ");
        if (words.length > 0 && stringsToRemoveSet.contains(words[0].toLowerCase())) {
            title = StringUtils.removeStartIgnoreCase(title, words[0]);
        } else if (words.length > 0 && stringsToRemoveSet.contains(words[words.length - 1].toLowerCase())) {
            title = StringUtils.removeEndIgnoreCase(title, words[words.length - 1]);
        } else {/*from   w w  w .j a  v a 2s .c  om*/
            break;
        }
    }
    return title;
}

From source file:org.ejbca.core.model.ca.catoken.CATokenContainerImpl.java

/**
 * Method that generates the keys that will be used by the CAToken.
 * The method can be used to generate keys for an initial CA token or to renew Certificate signing keys. 
 * If setstatustowaiting is true and you generate new keys, the new keys will be available as SecConst.CAKEYPURPOSE_CERTSIGN.
 * If setstatustowaiting is false and you generate new keys, the new keys will be available as SecConst.CAKEYPURPOSE_CERTSIGN_NEXT.
 * //w  w w.j  a v  a  2  s .  c  om
 * @param authenticationCode the password used to encrypt the keystore, later needed to activate CA Token
 * @param renew flag indicating if the keys are renewed instead of created fresh. Renewing keys does not 
 * create new encryption keys, since this would make it impossible to decrypt old stuff.
 * @param activate flag indicating if the new keys should be activated immediately or or they should be added as "next" signing key. 
 * Using true here makes it possible to generate certificate renewal requests for external CAs still using the old keys until the response is received. 
 */
public void generateKeys(final String authenticationCode, final boolean renew, final boolean activate)
        throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">generateKeys: " + (authenticationCode == null ? "null" : "hidden") + ", renew=" + renew
                + ", activate=" + activate);
    }
    CATokenInfo catokeninfo = getCATokenInfo();

    // First we start by setting a new sequence for our new keys
    String oldSequence = getKeySequence();
    log.debug("Current sequence: " + oldSequence);
    String newSequence = StringTools.incrementKeySequence(getCATokenInfo().getKeySequenceFormat(), oldSequence);
    // We store the sequence permanently in the object last, when we know everything went well

    // If we don't give an authentication code, perhaps we have autoactivation enabled
    char[] authCode = getAuthCodeOrAutoactivationPin(authenticationCode);

    String tokentype = null;

    // Then we can move on to actually generating the keys
    if (catokeninfo instanceof SoftCATokenInfo) {
        // If we have an existing soft keystore verify that the password is correct
        checkSoftKeystorePassword(authenticationCode);

        SoftCATokenInfo info = (SoftCATokenInfo) catokeninfo;

        Properties properties = getProperties();

        PublicKey pubEnc = null;
        PrivateKey privEnc = null;
        PublicKey previousPubSign = null;
        PrivateKey previousPrivSign = null;
        PublicKey oldPreviousPubSign = null;
        PrivateKey oldPreviousPrivSign = null;
        if (!renew) {
            log.debug("We are generating initial keys.");
            // Generate encryption keys.  
            // Encryption keys must be RSA still
            KeyPair enckeys = KeyTools.genKeys(info.getEncKeySpec(), info.getEncKeyAlgorithm());
            pubEnc = enckeys.getPublic();
            privEnc = enckeys.getPrivate();
        } else {
            log.debug("We are renewing keys.");
            // Get the already existing encryption and signature keys
            ICAToken token = getCAToken();
            pubEnc = token.getPublicKey(SecConst.CAKEYPURPOSE_KEYENCRYPT);
            privEnc = token.getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT);
            previousPubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN);
            previousPrivSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN);
            oldPreviousPubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
            oldPreviousPrivSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        }
        // As first choice we check if the used have specified which type of key should be generated, this can be different from the currently used key
        // If the user did not specify this, we try to generate a key with the same specification as the currently used key.
        String keyspec = info.getSignKeySpec(); // can be "unknown"
        if (StringUtils.equals(keyspec, AlgorithmTools.KEYSPEC_UNKNOWN)) {
            keyspec = null;
        }
        AlgorithmParameterSpec paramspec = KeyTools.getKeyGenSpec(previousPubSign);
        if (log.isDebugEnabled()) {
            if (keyspec != null) {
                log.debug("Generating new Soft key with specified spec " + keyspec + " with label "
                        + SoftCAToken.PRIVATESIGNKEYALIAS);
            } else {
                int keySize = KeyTools.getKeyLength(previousPubSign);
                String alg = previousPubSign.getAlgorithm();
                log.debug("Generating new Soft " + alg + " key with spec " + paramspec + " (size=" + keySize
                        + ") with label " + SoftCAToken.PRIVATESIGNKEYALIAS);
            }
        }
        // Generate signature keys.
        KeyPair newsignkeys = KeyTools.genKeys(keyspec, paramspec, info.getSignKeyAlgorithm());

        // Create the new keystore and add the new signature keys
        KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(null, null);

        // PLay with aliases depending on if we activate the new key or not
        String newSignKeyAlias = SoftCAToken.PRIVATESIGNKEYALIAS;
        String previousSignKeyAlias = SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS;
        if (!activate) {
            // If the new keys are not activated we must still use the old key as active signing key (PRIVATESIGNKEYALIAS)
            newSignKeyAlias = SoftCAToken.NEXTPRIVATESIGNKEYALIAS;
            previousSignKeyAlias = SoftCAToken.PRIVATESIGNKEYALIAS;
        }
        log.debug("Setting newsignkeys as " + newSignKeyAlias + " in soft CA token.");
        Certificate[] certchain = new Certificate[1]; // generate dummy certificate
        String sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(newsignkeys.getPublic()).iterator()
                .next();
        certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, newsignkeys.getPrivate(),
                newsignkeys.getPublic(), sigAlg, true);
        keystore.setKeyEntry(newSignKeyAlias, newsignkeys.getPrivate(), null, certchain);
        if (!activate) {
            log.debug("Set next sequence: " + newSequence);
            properties.setProperty(ICAToken.NEXT_SEQUENCE_PROPERTY, newSequence);
            log.debug("Set nextCertSignKey: " + newSignKeyAlias);
            properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_NEXT, newSignKeyAlias);
        }

        // If we have an old key (i.e. generating new keys), we will store the old one as "previous"
        if (previousPrivSign != null) {
            log.debug("Setting previousPrivSign as " + previousSignKeyAlias + " in soft CA token.");
            sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(previousPubSign).iterator().next();
            certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, previousPrivSign, previousPubSign,
                    sigAlg, true);
            keystore.setKeyEntry(previousSignKeyAlias, previousPrivSign, null, certchain);
            // Now this keystore should have this previous key
            if (activate) {
                // This key pair is now moved down to previous sign key
                properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, previousSignKeyAlias);
                // Set previous sequence so we can create link certificates
                log.debug("Set previous sequence : " + oldSequence);
                properties.setProperty(ICAToken.PREVIOUS_SEQUENCE_PROPERTY, oldSequence);
            } else {
                // If we have an old previous key and we are not activating the new key, we will keep this one as "previous"
                // If the new keys are activate the old previous keys are trashed and replaced by the old active signature key
                String prevProp = properties.getProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS); // If we don't have a previous key don't try to add it
                if ((oldPreviousPrivSign != null) && (prevProp != null)) {
                    log.debug("Setting old previousprivatesignkeyalias as "
                            + SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS + " in soft CA token.");
                    sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(oldPreviousPubSign).iterator()
                            .next();
                    certchain[0] = CertTools.genSelfCert("CN=dummy3", 36500, null, oldPreviousPrivSign,
                            oldPreviousPubSign, sigAlg, true);
                    keystore.setKeyEntry(SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS, oldPreviousPrivSign, null,
                            certchain);
                    properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS,
                            SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS);
                } else {
                    log.debug("No previousprivatesignkeyalias exists, not setting any previous key.");
                }
            }
        }

        // Finally install the old encryption/decryption keys as well
        sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(pubEnc).iterator().next();
        certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, privEnc, pubEnc, sigAlg, true);
        keystore.setKeyEntry(SoftCAToken.PRIVATEDECKEYALIAS, privEnc, null, certchain);

        storeSoftKeyStore(authCode, info, properties, keystore);
        tokentype = "Soft"; // for logging
    } else if (catokeninfo instanceof HardCATokenInfo) {
        ICAToken token = getCAToken();
        if (token instanceof PKCS11CAToken) {
            Properties properties = getProperties();
            PublicKey pubK = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN);
            String keyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CERTSIGN);
            log.debug("Old key label is: " + keyLabel);
            String crlKeyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CRLSIGN);
            // The key label to use for the new key
            // Remove the old sequence from the end of the key label and replace it with the
            // new label. If no label was present just concatenate the new label
            String newKeyLabel = StringUtils.removeEnd(keyLabel, oldSequence) + newSequence;
            log.debug("New key label is: " + newKeyLabel);

            final KeyStore.PasswordProtection pwp = new KeyStore.PasswordProtection(authCode);

            // As first choice we check if the used have specified which type of key should be generated, this can be different from the currently used key
            // If the user did not specify this, we try to generate a key with the same specification as the currently used key.
            String keyspec = properties.getProperty(ICAToken.KEYSPEC_PROPERTY); // can be null, and that is ok
            AlgorithmParameterSpec paramspec = KeyTools.getKeyGenSpec(pubK);
            if (log.isDebugEnabled()) {
                String sharedLibrary = properties.getProperty(PKCS11CAToken.SHLIB_LABEL_KEY);
                String slot = properties.getProperty(PKCS11CAToken.SLOT_LABEL_KEY);
                String attributesFile = properties.getProperty(PKCS11CAToken.ATTRIB_LABEL_KEY);
                if (keyspec != null) {
                    log.debug("Generating new PKCS#11 key with specified spec " + keyspec + " with label "
                            + newKeyLabel + ", on slot " + slot + ", using sharedLibrary " + sharedLibrary
                            + ", and attributesFile " + attributesFile);
                } else {
                    int keySize = KeyTools.getKeyLength(pubK);
                    String alg = pubK.getAlgorithm();
                    log.debug("Generating new PKCS#11 " + alg + " key with spec " + paramspec + " (size="
                            + keySize + ") with label " + newKeyLabel + ", on slot " + slot
                            + ", using sharedLibrary " + sharedLibrary + ", and attributesFile "
                            + attributesFile);
                }
            }
            KeyStoreContainer cont = KeyStoreContainerFactory
                    .getInstance(KeyStoreContainer.KEYSTORE_TYPE_PKCS11, token.getProvider(), pwp);
            cont.setPassPhraseLoadSave(authCode);
            if (keyspec != null) {
                log.debug("Generating from string keyspec: " + keyspec);
                cont.generate(keyspec, newKeyLabel);
            } else {
                log.debug("Generating from AlgorithmParameterSpec: " + paramspec);
                cont.generate(paramspec, newKeyLabel);
            }
            // Set properties so that we will start using the new key, or not, depending on the activate argument
            KeyStrings kstr = new KeyStrings(properties);
            String certsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CERTSIGN);
            log.debug("CAKEYPURPOSE_CERTSIGN keystring is: " + certsignkeystr);
            String crlsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CRLSIGN);
            log.debug("CAKEYPURPOSE_CRLSIGN keystring is: " + crlsignkeystr);
            if (!activate) {
                // If the new keys are not activated we must still use the old key as active signing key (PRIVATESIGNKEYALIAS)
                log.debug("Set nextCertSignKey: " + newKeyLabel);
                properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_NEXT, newKeyLabel);
                log.debug("Set next sequence: " + newSequence);
                properties.setProperty(ICAToken.NEXT_SEQUENCE_PROPERTY, newSequence);
            } else {
                properties.setProperty(certsignkeystr, newKeyLabel);
                properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, keyLabel);
                // If the key strings are not equal, i.e. crtSignKey and crlSignKey was used instead of just defaultKey
                // and the keys are the same. Then we need to set both keys to use the new key label
                if (!StringUtils.equals(certsignkeystr, crlsignkeystr)
                        && StringUtils.equals(keyLabel, crlKeyLabel)) {
                    log.debug("Also setting crlsignkeystr to " + newKeyLabel);
                    properties.setProperty(crlsignkeystr, newKeyLabel);
                }
                // Also set the previous sequence
                properties.setProperty(ICAToken.PREVIOUS_SEQUENCE_PROPERTY, oldSequence);
            }
            setProperties(properties);
            tokentype = "PKCS#11"; // for logging
        }
    } else {
        String msg = intres.getLocalizedMessage("catoken.genkeysnotavail");
        log.error(msg);
        return;
    }
    // Store the new sequence permanently. We should not do this earlier, because if an error is thrown generating keys we should not have updated the CA token object
    if (activate) {
        log.debug("Setting new sequence: " + newSequence);
        setKeySequence(newSequence);
    }
    // Finally reset the token so it will be re-read when we want to use it
    this.catoken = null;
    String msg = intres.getLocalizedMessage("catoken.generatedkeys", tokentype);
    log.info(msg);
    if (log.isTraceEnabled()) {
        log.trace("<generateKeys");
    }
}

From source file:org.entando.edo.parser.CommandlineParser.java

/**
 * Setta le opzioni e pulisce args!//w ww.ja  v  a 2s. com
 * @param cl
 * @param edoBean
 * @param args
 * @return
 * @throws IllegalArgumentException
 */
private String[] processCommandline(CommandLine cl, EdoBuilder edoBuilder, String[] args)
        throws IllegalArgumentException {
    if (cl.hasOption(OPTION_BASE_DIR)) {
        String baseDir = cl.getOptionValue(OPTION_BASE_DIR);
        if (StringUtils.isNotBlank(baseDir)) {
            if (baseDir.endsWith(File.separator)) {
                baseDir = StringUtils.removeEnd(baseDir, File.separator);
            }
            edoBuilder.setBaseDir(baseDir);
        }
    }
    _logger.debug("baseDir is: '{}'", edoBuilder.getBaseDir());

    if (cl.hasOption(OPTION_PERMISSION)) {
        String perm = cl.getOptionValue(OPTION_PERMISSION);
        if (StringUtils.isNotBlank(perm)) {
            edoBuilder.setPermission(perm);
        }
    }
    _logger.debug("permission is: '{}'", edoBuilder.getPermission());

    String packageName = null;
    if (cl.hasOption(OPTION_PACKAGE)) {
        String packageNameParam = cl.getOptionValue(OPTION_PACKAGE);
        if (StringUtils.isNotBlank(packageNameParam)) {
            if (PackageValidator.isValidPackageName(packageNameParam)) {
                packageName = packageNameParam;
            } else {
                _logger.error("invalid package name specified: {}", packageName);
                throw new IllegalArgumentException("invalid package name specified: " + packageName);
            }
        }
    } else {
        _logger.trace("auto generate packagename");
        if (!cl.getArgList().isEmpty()) {
            packageName = "org.entando.entando.plugins.jp" + cl.getArgs()[0].toLowerCase();
        } else {
            _logger.warn("Unable to generate the default package name. No enough args");
        }
    }

    edoBuilder.setPackageName(packageName);
    _logger.debug("packagename: is '{}'", edoBuilder.getPackageName());

    args = Arrays.copyOfRange(args, cl.getOptions().length, args.length);
    return args;
}

From source file:org.entando.entando.aps.system.services.storage.api.LocalStorageManagerInterface.java

public void addResource(JAXBStorageResource storageResource, Properties properties)
        throws ApiException, Throwable {
    try {//  ww w. j a  va  2 s  .c o m
        boolean isProtected = storageResource.isProtectedResource();
        //validate parent directory;
        String path = StringUtils.removeEnd(storageResource.getName(), "/");
        String parentFolder = FilenameUtils.getFullPathNoEndSeparator(path);
        if (StringUtils.isNotBlank(parentFolder))
            parentFolder = URLDecoder.decode(parentFolder, "UTF-8");
        if (!StorageManagerUtil.isValidDirName(parentFolder)) {
            throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "Invalid parent directory",
                    Response.Status.CONFLICT);
        }
        BasicFileAttributeView parentBasicFileAttributeView = this.getStorageManager()
                .getAttributes(parentFolder, isProtected);
        if (null == parentBasicFileAttributeView || !parentBasicFileAttributeView.isDirectory()) {
            throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "Invalid parent directory",
                    Response.Status.CONFLICT);
        }
        //validate exists
        BasicFileAttributeView basicFileAttributeView2 = this.getStorageManager().getAttributes(path,
                isProtected);
        if (null != basicFileAttributeView2) {
            throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "File already present",
                    Response.Status.CONFLICT);
        }

        String filename = StringUtils.substringAfter(storageResource.getName(), parentFolder);
        if (storageResource.isDirectory()) {
            if (!StorageManagerUtil.isValidDirName(filename)) {
                throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "Invalid dir name",
                        Response.Status.CONFLICT);
            }
            this.getStorageManager().createDirectory(storageResource.getName(), isProtected);
        } else {
            //validate file content
            if (!storageResource.isDirectory()
                    && (null == storageResource.getBase64() || storageResource.getBase64().length == 0)) {
                throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "A file cannot be empty",
                        Response.Status.CONFLICT);
            }
            if (!StorageManagerUtil.isValidFilename(filename)) {
                throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "Invalid filename name",
                        Response.Status.CONFLICT);
            }
            this.getStorageManager().saveFile(storageResource.getName(), isProtected,
                    new ByteArrayInputStream(storageResource.getBase64()));
        }
    } catch (ApiException ae) {

        throw ae;
    } catch (Throwable t) {
        _logger.error("Error adding new storage resource", t);
        throw t;
    }
}

From source file:org.entando.entando.aps.system.services.storage.api.LocalStorageManagerInterface.java

public void deleteResource(Properties properties) throws ApiException, Throwable {
    String pathValue = properties.getProperty(PARAM_PATH);
    String protectedValue = properties.getProperty(PARAM_IS_PROTECTED);
    boolean isProtected = StringUtils.equalsIgnoreCase(protectedValue, "true");
    try {/*from w  ww.ja v a2s. c  om*/
        if (StringUtils.isNotBlank(pathValue))
            pathValue = URLDecoder.decode(pathValue, "UTF-8");
        String path = StringUtils.removeEnd(pathValue, "/");
        String parentFolder = FilenameUtils.getFullPathNoEndSeparator(path);
        BasicFileAttributeView parentBasicFileAttributeView = this.getStorageManager()
                .getAttributes(parentFolder, isProtected);
        if (null == parentBasicFileAttributeView || !parentBasicFileAttributeView.isDirectory()) {
            throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "Invalid parent directory",
                    Response.Status.CONFLICT);
        }
        if (!StorageManagerUtil.isValidDirName(parentFolder)) {
            throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "Invalid parent directory",
                    Response.Status.CONFLICT);
        }
        BasicFileAttributeView basicFileAttributeView = this.getStorageManager().getAttributes(pathValue,
                isProtected);
        if (null == basicFileAttributeView) {
            throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "The file does not exists",
                    Response.Status.CONFLICT);
        }
        String filename = StringUtils.substringAfter(pathValue, parentFolder);
        if (basicFileAttributeView.isDirectory()) {
            if (!StorageManagerUtil.isValidDirName(filename)) {
                throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "Invalid dir name",
                        Response.Status.CONFLICT);
            }
            String recursiveDelete = properties.getProperty(PARAM_DELETE_RECURSIVE);
            boolean isRecursiveDelete = StringUtils.equalsIgnoreCase(recursiveDelete, "true");
            if (!isRecursiveDelete) {
                String[] dirContents = this.getStorageManager().list(pathValue, isProtected);
                if (null != dirContents && dirContents.length > 0) {
                    throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "The directory is not empty",
                            Response.Status.CONFLICT);
                }
            }
            this.getStorageManager().deleteDirectory(pathValue, isProtected);
        } else {
            //it's a file
            if (!StorageManagerUtil.isValidFilename(filename)) {
                throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "Invalid filename",
                        Response.Status.CONFLICT);
            }
            this.getStorageManager().deleteFile(pathValue, isProtected);
        }

    } catch (ApiException ae) {

        throw ae;
    } catch (Throwable t) {
        _logger.error("Error adding new storage resource", t);
        throw t;
    }
}

From source file:org.executequery.gui.editor.QueryEditorTextPane.java

public void moveSelectionUp() {

    try {/*from w  ww . j  a v a  2s. c om*/

        int start = getStartOffsetAtSelectionOrCursor();
        if (start == 0) {

            return;
        }
        int end = getEndOffsetAtSelectionOrCursor();

        int previousRow = getRowAt(start) - 1;
        String previousRowText = getTextAtRow(previousRow);
        if (previousRowText == null) {

            return;
        }

        String textToMove = getText(start, (end - start));
        String textToInsert = textToMove + previousRowText;

        if (getRowAt(end) == getRowAt(end - 1)) {

            textToInsert = StringUtils.removeEnd(textToInsert, "\n");

        }

        int insertLength = textToInsert.length();
        int insertAt = getRowStartOffset(previousRow);
        if (insertAt + insertLength > getDocument().getLength()) {

            insertLength--;
        }

        getDocument().remove(insertAt, insertLength);
        insertTextAtOffset(insertAt, textToInsert);

        setSelectionStart(insertAt);
        setSelectionEnd(insertAt + textToMove.length());

    } catch (BadLocationException e) {

        return;
    }
}

From source file:org.executequery.gui.editor.QueryEditorTextPane.java

public void moveSelectionDown() {

    try {//from www.  jav a  2  s  .com

        int start = getStartOffsetAtSelectionOrCursor();
        int end = getEndOffsetAtSelectionOrCursor();

        int nextRow = getRowAt(end);
        String nextRowText = getTextAtRow(nextRow);
        if (nextRowText == null) {

            return;
        }

        String textToMove = StringUtils.removeEnd(getText(start, (end - start)), "\n");
        String textToInsert = nextRowText + textToMove;

        int insertLength = textToInsert.length();
        if (start + insertLength > getDocument().getLength()) {

            insertLength--;
        }

        getDocument().remove(start, insertLength);
        insertTextAtOffset(start, textToInsert);

        int selectionStart = start + nextRowText.length();
        setSelectionStart(selectionStart);
        setSelectionEnd(selectionStart + textToMove.length() + 1);

    } catch (BadLocationException e) {

        return;
    }
}

From source file:org.executequery.gui.editor.QueryEditorTextPane.java

private void duplicateSelectionOrRowToOffset(int direction) {

    try {/*  w  ww  . j a  va  2 s.co  m*/

        int start = getStartOffsetAtSelectionOrCursor();
        int end = getEndOffsetAtSelectionOrCursor();

        int offset = 0;
        int selectionOffset = 0;

        String insertText = getText(start, (end - start));
        insertText = StringUtils.removeEnd(insertText, "\n");

        if (direction == DIRECTION_UP) {

            insertText += "\n";
            offset = start;
            selectionOffset = offset;

        } else {

            insertText = "\n" + insertText;
            offset = end - 1;
            selectionOffset = offset + 1;

            if (StringUtils.isWhitespace(insertText) && getLastRow() == getRowAt(end)) {

                return;
            }

        }

        insertTextAtOffset(offset, insertText);
        setCaretPosition(offset + insertText.length());
        moveCaretPosition(selectionOffset);

    } catch (Exception e) {
    }

}

From source file:org.failearly.dataz.internal.template.support.test.message.basic.AbstractTemplateObjectMessage.java

private String generateBaseName(MessageArgumentsImpl.Accessor accessor) {
    return StringUtils.removeEnd(accessor.getValue(ARG_TEST_CLASS, String.class, UNKNOWN), "Test");
}

From source file:org.gradle.api.internal.tasks.compile.incremental.deps.ClassSetAnalysisData.java

public DependentsSet getDependents(String className) {
    if (fullRebuildCause != null) {
        return DependentsSet.dependencyToAll(fullRebuildCause);
    }//from  w w  w  .ja v a  2 s .c  o m
    if (className.endsWith(PACKAGE_INFO)) {
        String packageName = className.equals(PACKAGE_INFO) ? null
                : StringUtils.removeEnd(className, "." + PACKAGE_INFO);
        return getDependentsOfPackage(packageName);
    }
    DependentsSet dependentsSet = dependents.get(className);
    return dependentsSet == null ? DependentsSet.empty() : dependentsSet;
}