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

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

Introduction

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

Prototype

public static String stripStart(final String str, final String stripChars) 

Source Link

Document

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

A null input String returns null .

Usage

From source file:com.threadswarm.imagefeedarchiver.processor.RssItemProcessor.java

private void downloadRssMediaContent(ProcessedRssItem processedItem, RssMediaContent mediaContent) {
    DownloadStatus downloadStatus = DownloadStatus.FAILED;
    HttpEntity responseEntity = null;/*from   w  ww .j a va2 s  .  co m*/
    try {
        String targetUrlString = mediaContent.getUrlString();
        if (forceHttps)
            targetUrlString = FeedUtils.rewriteUrlStringToHttps(targetUrlString);

        URI targetURI = FeedUtils.getUriFromUrlString(targetUrlString);

        boolean freshURI = processedURISet.add(targetURI);
        if (!freshURI) {
            LOGGER.warn("Skipping previously processed URI: {}", targetURI);
            return; //abort processing
        }

        LOGGER.info("Attempting to download {}", targetURI);
        HttpGet imageGet = new HttpGet(targetURI);

        for (Header header : headerList)
            imageGet.addHeader(header);

        HttpResponse imageResponse = httpClient.execute(imageGet);

        String originalFileName = StringUtils.stripStart(targetURI.toURL().getFile(), "/");
        originalFileName = StringUtils.replace(originalFileName, "/", "_");
        File outputFile = getOutputFile(originalFileName);

        long expectedContentLength = FeedUtils.calculateBestExpectedContentLength(imageResponse, mediaContent);
        responseEntity = imageResponse.getEntity();

        BufferedInputStream bis = null;
        DigestOutputStream fos = null;
        int bytesRead = 0;
        try {
            bis = new BufferedInputStream(responseEntity.getContent());
            fos = new DigestOutputStream(new FileOutputStream(outputFile), MessageDigest.getInstance("SHA"));

            byte[] buffer = new byte[8192];
            while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            fos.flush();

            MessageDigest messageDigest = fos.getMessageDigest();
            byte[] digestBytes = messageDigest.digest();
            String digestString = Hex.encodeHexString(digestBytes);
            LOGGER.info("Downloaded - {} (SHA: {})", targetURI, digestString);

            processedItem.setDownloadDate(new Date());
            downloadStatus = DownloadStatus.COMPLETED;
            processedItem.setHash(digestString);
            processedItem.setFilename(outputFile.toString());
        } catch (ConnectionClosedException e) {
            LOGGER.error("An Exception was thrown while attempting to read HTTP entity content", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("The SHA-1 hashing algorithm is not available on this JVM", e);
        } finally {
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(fos);
            EntityUtils.consumeQuietly(responseEntity);
            if (downloadStatus == DownloadStatus.FAILED
                    || (outputFile.exists() && outputFile.length() != expectedContentLength)) {
                LOGGER.warn("Deleted partial/failed file: {}", outputFile);
                outputFile.delete();
                processedItem.setDownloadStatus(DownloadStatus.FAILED);
            }
        }
    } catch (IOException e) {
        LOGGER.error("An Exception was thrown while attempting to download image content", e);
    } catch (URISyntaxException e) {
        LOGGER.error("The supplied URI, {}, violates syntax rules", e);
    } finally {
        EntityUtils.consumeQuietly(responseEntity);
    }

    processedItem.setDownloadStatus(downloadStatus);
    itemDAO.save(processedItem);
}

From source file:com.creapple.tms.mobiledriverconsole.utils.MDCUtils.java

/**
 * Bring up Stop groups per interval as String array
 * @param data//from  www .ja v  a  2s.  com
 * @return
 */
public static String[] getStopGroups(String data) {
    String[] stops = null;
    if (data != null && data.length() > 0) {
        String start = StringUtils.stripStart(data, "[[");
        String end = StringUtils.stripEnd(start, "]]");
        stops = StringUtils.splitByWholeSeparator(end, "],[");
    }
    return stops;
}

From source file:io.wcm.handler.media.impl.AbstractMediaFileServlet.java

/**
 * Send binary data to output stream. Respect optional content disposition header handling.
 * @param binaryData Binary data array.// ww  w .j a v  a 2s  .c o m
 * @param contentType Content type
 * @param request Request
 * @param response Response
 * @throws IOException
 */
protected void sendBinaryData(byte[] binaryData, String contentType, SlingHttpServletRequest request,
        SlingHttpServletResponse response) throws IOException {

    // set content type and length
    response.setContentType(contentType);
    response.setContentLength(binaryData.length);

    // Handling of the "force download" selector
    if (RequestPath.hasSelector(request, SELECTOR_DOWNLOAD)) {
        // Overwrite MIME type with one suited for downloads
        response.setContentType(ContentType.DOWNLOAD);

        // Construct disposition header
        StringBuilder dispositionHeader = new StringBuilder("attachment;");
        String suffix = request.getRequestPathInfo().getSuffix();
        suffix = StringUtils.stripStart(suffix, "/");
        if (StringUtils.isNotEmpty(suffix)) {
            dispositionHeader.append("filename=\"").append(suffix).append('\"');
        }

        response.setHeader(HEADER_CONTENT_DISPOSITION, dispositionHeader.toString());
    }

    // write binary data
    OutputStream out = response.getOutputStream();
    out.write(binaryData);
    out.flush();

}

From source file:com.thruzero.common.core.fs.walker.visitor.ZipCompressingVisitor.java

protected String getRelativePath(final File file) {
    // make relative path
    String relativePath = StringUtils.remove(file.getAbsolutePath(), rootDirectory.getAbsolutePath());

    if (StringUtils.isEmpty(relativePath)) {
        return StringUtils.EMPTY;
    }/* www  .j  a  v  a2  s  .  c  om*/

    return StringUtils.stripStart(relativePath, String.valueOf(File.separatorChar));
}

From source file:io.stallion.dataAccess.db.SqlMigrationAction.java

public List<SqlMigration> getUserMigrations() {
    List<SqlMigration> migrations = list();
    File sqlDirectory = new File(settings().getTargetFolder() + "/sql");
    if (!sqlDirectory.isDirectory()) {
        Log.finer("Sql directory does not exist {0}", sqlDirectory.getAbsoluteFile());
        return migrations;
    }//from  ww w.j a  v  a 2  s .  c  o  m
    Log.finer("Find sql files in {0}", sqlDirectory.getAbsolutePath());
    for (File file : sqlDirectory.listFiles()) {
        Log.finer("Scan file" + file.getAbsolutePath());
        if (!set("js", "sql").contains(FilenameUtils.getExtension(file.getAbsolutePath()))) {
            Log.finer("Extension is not .js or .sql {0}", file.getAbsolutePath());
            continue;
        }
        if (file.getName().startsWith(".") || file.getName().startsWith("#")) {
            Log.finer("File name starts with invalid character {0}", file.getName());
            continue;
        }
        if (!file.getName().contains("." + DB.instance().getDbImplementation().getName().toLowerCase() + ".")) {
            Log.finer("File name does not contain the name of the current database engine: \".{0}.\"",
                    DB.instance().getDbImplementation().getName().toLowerCase());
            continue;
        }
        if (!file.getName().contains("-")) {
            Log.finer("File name does not have version part {0}", file.getName());
            continue;
        }
        String versionString = StringUtils.stripStart(StringUtils.split(file.getName(), "-")[0], "0");
        if (!StringUtils.isNumeric(versionString)) {
            Log.finer("File name does not have numeric version part {0}", file.getName());
            continue;
        }
        Log.info("Load SQL file for migration: {0}", file.getName());

        migrations.add(new SqlMigration()
                .setVersionNumber(Integer.parseInt(StringUtils.stripStart(versionString, "0"))).setAppName("")
                .setFilename(file.getName()).setSource(FileUtils.readAllText(file)));
    }
    migrations.sort(new PropertyComparator<>("versionNumber"));
    return migrations;
}

From source file:io.stallion.dataAccess.file.FilePersisterBase.java

public void onPostLoadFromFile(T obj, String path) {
    if (path.startsWith(getBucketFolderPath())) {
        path = path.replace(getBucketFolderPath(), "");
    }/*from  ww w .ja v a  2  s  .c  om*/
    if (path.startsWith("/")) {
        path = StringUtils.stripStart(path, "/");
    }
    getIdToFileMap().put(obj.getId(), path);
    getFileToIdMap().put(path, obj.getId());
    if (obj instanceof ModelWithFilePath) {
        ((ModelWithFilePath) obj).setFilePath(path);
    }

}

From source file:io.stallion.dataAccess.db.SqlGenerationAction.java

public int getLastMigrationNumber() {
    Integer max = 0;/*ww  w .  ja  v a 2 s.  c  o  m*/
    File migrationsFile = new File(System.getProperty("user.dir") + "/src/main/resources/sql/migrations.txt");
    if (migrationsFile.exists()) {
        for (String line : FileUtils.readAllText(migrationsFile, UTF8).split("\\n")) {
            line = StringUtils.strip(line);
            if (empty(line)) {
                continue;
            }
            if (line.startsWith("//") || line.startsWith("#")) {
                continue;
            }
            int dash = line.indexOf("-");
            if (dash == -1) {
                continue;
            }
            Integer version = Integer.valueOf(StringUtils.stripStart(line.substring(0, dash), "0"));
            if (version >= max) {
                max = version;
            }
        }

    } else {
        for (SqlMigration migration : new SqlMigrationAction().getUserMigrations()) {
            if (migration.getVersionNumber() > max) {
                max = migration.getVersionNumber();
            }
        }
    }
    return max;
}

From source file:de.micromata.genome.gwiki.page.gspt.ExtendedTemplate.java

/**
 * Strip leading ws./* w w  w  .j  a v a2  s .com*/
 *
 * @param elements the elements
 */
private void stripLeadingWs(List<ParseElement> elements) {
    for (int i = 0; i < elements.size(); ++i) {
        if (elements.get(i).type == Type.Comment || elements.get(i).type == Type.Code
                || elements.get(i).type == Type.GlobalCode || elements.get(i).type == Type.ClassCode
                || elements.get(i).type == Type.Statement)
            continue;
        if (elements.get(i).type != Type.ConstString)
            break;
        String t = StringUtils.stripStart(elements.get(i).text.toString(), " \t\r\n");
        if (StringUtils.isEmpty(t) == true) {
            elements.remove(i);
            --i;
        } else {
            elements.get(i).text = new StringBuilder(t);
            break;
        }
    }
}

From source file:net.launchpad.jabref.plugins.ZentralSearch.java

private String constructQuery(String key) throws UnsupportedEncodingException {
    String query = "";
    if (StringUtils.isNotBlank(key)) {
        query += "any=" + URLEncoder.encode(key, CHARSET);
    }/*w w  w .  j a  v  a 2  s  .  co m*/
    ;
    if (StringUtils.isNotBlank(author.getText())) {
        query += "&au=" + URLEncoder.encode(author.getText(), CHARSET);
    }
    ;
    if (StringUtils.isNotBlank(title.getText())) {
        query += "&ti=" + URLEncoder.encode(title.getText(), CHARSET);
    }
    if (StringUtils.isNotBlank(theAbstract.getText())) {
        query += "&ab=" + URLEncoder.encode(theAbstract.getText(), CHARSET);
    }
    query = StringUtils.stripStart(query, "&");
    return query;
}

From source file:io.stallion.utils.GeneralUtils.java

/**
 * Turn the given long id into a random base32 string token. This can be used for generating unique, secret strings
 * for accessing data, such as a web page only viewable by a secret string. By using the long id, of the
 * underlying object we guarantee uniqueness, by adding on  random characters, we make the URL nigh
 * impossible to guess.//from w  w w  .j  a v  a  2 s  .  c om
 *
 * @param id - a long id that will be convered to base32 and used as the first part of the string
 * @param length - the number of random base32 characters to add to the end of the string
 * @return
 */
public static String tokenForId(Long id, int length) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.putLong(id);
    return StringUtils.stripStart(new Base32().encodeAsString(buffer.array()), "A").replace("=", "")
            .toLowerCase() + "8" + randomTokenBase32(length);
}