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

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

Introduction

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

Prototype

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

Source Link

Document

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

A null source string will return null .

Usage

From source file:com.netflix.spinnaker.echo.pipelinetriggers.eventhandlers.GitEventHandler.java

private boolean hasValidGitHubSecureSignature(GitEvent gitEvent, Trigger trigger) {
    String header = gitEvent.getDetails().getRequestHeaders().getFirst(GITHUB_SECURE_SIGNATURE_HEADER);
    log.debug("GitHub Signature detected. " + GITHUB_SECURE_SIGNATURE_HEADER + ": " + header);
    String signature = StringUtils.removeStart(header, "sha1=");

    String computedDigest = HmacUtils.hmacSha1Hex(trigger.getSecret(), gitEvent.getRawContent());

    // TODO: Find constant time comparison algo?
    boolean digestsMatch = signature.equalsIgnoreCase(computedDigest);
    if (!digestsMatch) {
        log.warn("Github Digest mismatch! Pipeline NOT triggered: " + trigger);
        log.debug("computedDigest: " + computedDigest + ", from GitHub: " + signature);
    }//  ww w  .j  a va2  s.c  om

    return digestsMatch;
}

From source file:com.axibase.tsd.client.PlainSender.java

@Override
public void writeTo(OutputStream outputStream) throws IOException {
    String marker = null;/*from  www.ja va2s  . c om*/
    while (state == SenderState.WORKING) {
        String message = null;
        try {
            message = messages.poll(pingTimeoutMillis, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            if (state != SenderState.WORKING) {
                log.error("Could not poll message from queue", e);
            }
        }

        try {
            if (message != null) {
                if (!clientConfiguration.isSkipStreamingControl()) {
                    if (marker == null && !message.startsWith(MARKER_KEYWORD)) {
                        MarkerCommand markerCommand = new MarkerCommand();
                        marker = markerCommand.getMarker();
                        write(outputStream, markerCommand.compose());
                    }
                }

                log.debug("Write message: {}", message);
                write(outputStream, message);

                if (!clientConfiguration.isSkipStreamingControl()) {
                    if (message.startsWith(MARKER_KEYWORD)) {
                        marker = StringUtils.removeStart(message, MARKER_KEYWORD).trim();
                        if (StringUtils.isBlank(marker)) {
                            throw new IllegalArgumentException("Bad marker message: " + message);
                        }
                    } else {
                        add(marker, message);
                    }
                }

                lastMessageTime = System.currentTimeMillis();
            }
        } catch (Throwable e) {
            log.error("Sender is broken, close it. Could not send message: {}", message, e);
            messages.add(message);
            close();
            return;
        }
        if (lastMessageTime - System.currentTimeMillis() > pingTimeoutMillis) {
            write(outputStream, PING_COMMAND);
            if (!clientConfiguration.isSkipStreamingControl()) {
                add(marker, PING_COMMAND);
            }
            lastMessageTime = System.currentTimeMillis();
        }
    }
}

From source file:com.infinities.keystone4j.AbstractAction.java

protected String getBaseUrl(ContainerRequestContext context, String path) {
    String endpoint = Wsgi.getBaseUrl(context, "public");
    if (Strings.isNullOrEmpty(path)) {
        path = getCollectionName();/*  www  . j  a  v  a2s  .  co m*/
    }
    String ret = String.format("%s/%s/%s", endpoint, "v3", StringUtils.removeStart(path, "/"));
    if (ret.endsWith("/")) {
        ret = ret.substring(0, ret.length() - 1);
    }
    return ret;
}

From source file:com.sonicle.webtop.vfs.bol.model.SharingLink.java

public String relativizePath(String path) {
    return PathUtils.ensureBeginningSeparator(StringUtils.removeStart(path, getFilePath()));
}

From source file:eu.sisob.uma.footils.File.FileFootils.java

public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection)
        throws IOException {

    final JarFile jarFile = jarConnection.getJarFile();

    for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
        final JarEntry entry = e.nextElement();
        if (entry.getName().startsWith(jarConnection.getEntryName())) {
            final String filename = StringUtils.removeStart(entry.getName(), //
                    jarConnection.getEntryName());

            final File f = new File(destDir, filename);
            if (!entry.isDirectory()) {
                final InputStream entryInputStream = jarFile.getInputStream(entry);
                if (!FileFootils.copyStream(entryInputStream, f)) {
                    return false;
                }/*from  ww w. j a  v a  2  s  .  c o  m*/
                entryInputStream.close();
            } else {
                if (!FileFootils.ensureDirectoryExists(f)) {
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    return true;
}

From source file:com.infinities.keystone4j.assignment.controller.action.roleassignment.AbstractRoleAssignmentAction.java

protected String getBaseUrl(ContainerRequestContext context, String path) {
    String endpoint = Wsgi.getBaseUrl(context, "public");
    if (Strings.isNullOrEmpty(path)) {
        path = getCollectionName();//  ww  w  . j  a  va 2  s.c om
    }

    String ret = String.format("%s/%s/%s", endpoint, "v3", StringUtils.removeStart(path, "/"));
    if (ret.endsWith("/")) {
        ret = ret.substring(0, ret.length() - 1);
    }
    return ret;
}

From source file:alpine.resources.AlpineResource.java

/**
 * Accepts the result from one of the many validation methods available and
 * returns a List of ValidationErrors. If the size of the List is 0, no errors
 * were encounter during validation./*from www. jav a  2 s  . c  o  m*/
 *
 * Usage:
 * <pre>
 *     Validator validator = getValidator();
 *     List&lt;ValidationError&gt; errors = contOnValidationError(
 *         validator.validateProperty(myObject, "uuid"),
 *         validator.validateProperty(myObject, "name")
 *      );
 *      // If validation fails, this line will be reached.
 * </pre>
 *
 * @param violationsArray a Set of one or more ConstraintViolations
 * @return a List of zero or more ValidationErrors
 * @since 1.0.0
 */
@SafeVarargs
protected final List<ValidationError> contOnValidationError(
        final Set<ConstraintViolation<Object>>... violationsArray) {
    final List<ValidationError> errors = new ArrayList<>();
    for (Set<ConstraintViolation<Object>> violations : violationsArray) {
        for (ConstraintViolation violation : violations) {
            if (violation.getPropertyPath().iterator().next().getName() != null) {
                final String path = violation.getPropertyPath() != null ? violation.getPropertyPath().toString()
                        : null;
                final String message = violation.getMessage() != null
                        ? StringUtils.removeStart(violation.getMessage(), path + ".")
                        : null;
                final String messageTemplate = violation.getMessageTemplate();
                final String invalidValue = violation.getInvalidValue() != null
                        ? violation.getInvalidValue().toString()
                        : null;
                final ValidationError error = new ValidationError(message, messageTemplate, path, invalidValue);
                errors.add(error);
            }
        }
    }
    return errors;
}

From source file:ch.cyberduck.core.b2.B2ObjectListService.java

/**
 * @param response List filenames response from server
 * @return Null when respone filename is not child of working directory directory
 *///from  www. ja  v  a2  s .c  om
protected PathAttributes parse(final B2FileInfoResponse response) {
    final PathAttributes attributes = new PathAttributes();
    attributes.setChecksum(Checksum.parse(StringUtils
            .removeStart(StringUtils.lowerCase(response.getContentSha1(), Locale.ROOT), "unverified:")));
    final long timestamp = response.getUploadTimestamp();
    if (response.getFileInfo().containsKey(X_BZ_INFO_SRC_LAST_MODIFIED_MILLIS)) {
        attributes.setModificationDate(
                Long.valueOf(response.getFileInfo().get(X_BZ_INFO_SRC_LAST_MODIFIED_MILLIS)));
    } else {
        attributes.setModificationDate(timestamp);
    }
    attributes.setVersionId(response.getFileId());
    switch (response.getAction()) {
    case hide:
        // File version marking the file as hidden, so that it will not show up in b2_list_file_names
    case start:
        // Large file has been started, but not finished or canceled
        attributes.setDuplicate(true);
        attributes.setSize(-1L);
        break;
    default:
        attributes.setSize(response.getSize());
    }
    return attributes;
}

From source file:com.xpn.xwiki.internal.filter.input.AbstractInstanceInputFilterStreamTest.java

protected void assertXML(String resource, InstanceInputProperties instanceProperties)
        throws FilterException, IOException {
    if (instanceProperties == null) {
        instanceProperties = new InstanceInputProperties();
        instanceProperties.setVerbose(false);
    }// w  ww .j a v a 2 s.  c o  m

    URL url = getClass().getResource("/filter/" + resource + ".xml");

    String expected = IOUtils.toString(url, "UTF-8");

    expected = StringUtils.removeStart(expected, "<?xml version=\"1.1\" encoding=\"UTF-8\"?>\n\n");

    InputFilterStream inputFilterStream = this.inputFilterStreamFactory
            .createInputFilterStream(instanceProperties);

    StringWriterOutputTarget writer = new StringWriterOutputTarget();

    FilterXMLOutputProperties properties = new FilterXMLOutputProperties();
    properties.setTarget(writer);

    OutputFilterStream outputFilterStream = this.xmlOutputFilterStreamFactory
            .createOutputFilterStream(properties);

    inputFilterStream.read(outputFilterStream.getFilter());

    inputFilterStream.close();
    outputFilterStream.close();

    Assert.assertEquals(expected, writer.getBuffer().toString());
}

From source file:ch.cyberduck.core.transfer.download.AbstractDownloadFilter.java

@Override
public TransferStatus prepare(final Path file, final Local local, final TransferStatus parent,
        final ProgressListener progress) throws BackgroundException {
    final TransferStatus status = new TransferStatus();
    if (parent.isExists()) {
        if (local.exists()) {
            if (file.getType().contains(Path.Type.file)) {
                if (local.isDirectory()) {
                    throw new LocalAccessDeniedException(String.format("Cannot replace folder %s with file %s",
                            local.getAbbreviatedPath(), file.getName()));
                }/*from  ww w  .j  a v a2  s . co m*/
            }
            if (file.getType().contains(Path.Type.directory)) {
                if (local.isFile()) {
                    throw new LocalAccessDeniedException(String.format("Cannot replace file %s with folder %s",
                            local.getAbbreviatedPath(), file.getName()));
                }
            }
            status.setExists(true);
        }
    }
    final PathAttributes attributes;
    if (file.isSymbolicLink()) {
        // A server will resolve the symbolic link when the file is requested.
        final Path target = file.getSymlinkTarget();
        // Read remote attributes of symlink target
        attributes = attribute.find(target);
        if (!symlinkResolver.resolve(file)) {
            if (file.isFile()) {
                // Content length
                status.setLength(attributes.getSize());
            }
        }
        // No file size increase for symbolic link to be created locally
    } else {
        // Read remote attributes
        attributes = attribute.find(file);
        if (file.isFile()) {
            // Content length
            status.setLength(attributes.getSize());
            if (StringUtils.startsWith(attributes.getDisplayname(), "file:")) {
                final String filename = StringUtils.removeStart(attributes.getDisplayname(), "file:");
                if (!StringUtils.equals(file.getName(), filename)) {
                    status.withDisplayname(LocalFactory.get(local.getParent(), filename));
                    int no = 0;
                    while (status.getDisplayname().local.exists()) {
                        String proposal = String.format("%s-%d", FilenameUtils.getBaseName(filename), ++no);
                        if (StringUtils.isNotBlank(FilenameUtils.getExtension(filename))) {
                            proposal += String.format(".%s", FilenameUtils.getExtension(filename));
                        }
                        status.withDisplayname(LocalFactory.get(local.getParent(), proposal));
                    }
                }
            }
        }
    }
    status.setRemote(attributes);
    if (options.timestamp) {
        status.setTimestamp(attributes.getModificationDate());
    }
    if (options.permissions) {
        Permission permission = Permission.EMPTY;
        if (preferences.getBoolean("queue.download.permissions.default")) {
            if (file.isFile()) {
                permission = new Permission(preferences.getInteger("queue.download.permissions.file.default"));
            }
            if (file.isDirectory()) {
                permission = new Permission(
                        preferences.getInteger("queue.download.permissions.folder.default"));
            }
        } else {
            permission = attributes.getPermission();
        }
        status.setPermission(permission);
    }
    status.setAcl(attributes.getAcl());
    if (options.segments) {
        if (file.isFile()) {
            // Make segments
            if (status.getLength() >= preferences.getLong("queue.download.segments.threshold")
                    && status.getLength() > preferences.getLong("queue.download.segments.size")) {
                final Download read = session.getFeature(Download.class);
                if (read.offset(file)) {
                    if (log.isInfoEnabled()) {
                        log.info(String.format("Split download %s into segments", local));
                    }
                    long remaining = status.getLength();
                    long offset = 0;
                    // Part size from default setting of size divided by maximum number of connections
                    long partsize = Math.max(preferences.getLong("queue.download.segments.size"),
                            status.getLength() / preferences.getInteger("queue.connections.limit"));
                    // Sorted list
                    final List<TransferStatus> segments = new ArrayList<TransferStatus>();
                    final Local segmentsFolder = LocalFactory.get(local.getParent(),
                            String.format("%s.cyberducksegment", local.getName()));
                    for (int segmentNumber = 1; remaining > 0; segmentNumber++) {
                        final Local segmentFile = LocalFactory.get(segmentsFolder,
                                String.format("%s-%d.cyberducksegment", local.getName(), segmentNumber));
                        boolean skip = false;
                        // Last part can be less than 5 MB. Adjust part size.
                        Long length = Math.min(partsize, remaining);
                        final TransferStatus segmentStatus = new TransferStatus().segment(true).append(true)
                                .skip(offset).length(length).rename(segmentFile);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format("Adding status %s for segment %s", segmentStatus,
                                    segmentFile));
                        }
                        segments.add(segmentStatus);
                        remaining -= length;
                        offset += length;
                    }
                    status.withSegments(segments);
                }
            }
        }
    }
    if (options.checksum) {
        status.setChecksum(attributes.getChecksum());
    }
    return status;
}