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.sludev.commons.vfs2.provider.azure.AzFileObject.java

/**
 * Convenience method that returns the container and path from the current URL.
 * /*from  w ww  .  j  a v  a2s . com*/
 * @return A tuple containing the container name and the path.
 */
protected Pair<String, String> getContainerAndPath() {
    Pair<String, String> res = null;

    try {
        URLFileName currName = (URLFileName) getName();

        String currNameStr = currName.getPath();
        currNameStr = StringUtils.stripStart(currNameStr, "/");

        if (StringUtils.isBlank(currNameStr)) {
            log.warn(String.format("getContainerAndPath() : Path '%s' does not appear to be valid",
                    currNameStr));

            return null;
        }

        // Deal with the special case of the container root.
        if (StringUtils.contains(currNameStr, "/") == false) {
            // Container and root
            return new ImmutablePair<>(currNameStr, "/");
        }

        String[] resArray = StringUtils.split(currNameStr, "/", 2);

        res = new ImmutablePair<>(resArray[0], resArray[1]);
    } catch (Exception ex) {
        log.error(String.format("getContainerAndPath() : Path does not appear to be valid"), ex);
    }

    return res;
}

From source file:com.quartercode.jtimber.rh.agent.util.ResourceLister.java

/**
 * Creates a new resource lister that lists all occurrences of the given classpath resource on the classpath as {@link Path}s.
 * It is possible that multiple paths are listed if multiple classpath entries (e.g. jars) contain the resource.
 * For example, if two jars contain the directory {@code /test1/test2}, this class lists both both.<br>
 * <br>/*from  w w  w  . ja va  2s . c o m*/
 * Note that this class uses a workaround to create path objects for files which are located inside a jar.
 * Because of that, each instance of this class should be closed after the paths have been used.
 * However, the paths might no longer be accessible after the lister has been closed.
 * 
 * @param resourcePath The path that defines the classpath resource whose occurrences should be listed.
 * @param throwAll Whether {@link IOException}s, which are thrown during the retrieval of one specific resource and would therefore also interrupt
 *        the retrieval of other resources, should be thrown.
 *        If this is {@code false}, the regarding exceptions are logged as errors.
 * @throws IOException Something goes wrong while retrieving the resource occurrences.
 *         If {@code throwAll} is {@code true} and an occurrence is located inside a jar, a jar reading exception is also possible.
 * @throws IllegalArgumentException The resource path doesn't start with "/" (this method cannot list relative resources).
 * @see #getResourcePaths()
 */
public ResourceLister(String resourcePath, boolean throwAll) throws IOException {

    Validate.isTrue(resourcePath.startsWith("/"),
            "Cannot retrieve relative resources, make sure your path starts with '/'");

    // Retrieve all occurrences of the given path in the classpath
    Enumeration<URL> locations = ResourceLister.class.getClassLoader()
            .getResources(StringUtils.stripStart(resourcePath, "/"));

    // Iterate over those occurrences
    while (locations.hasMoreElements()) {
        URL location = locations.nextElement();

        // Check whether the found location is inside a jar file
        if (location.getProtocol().equals("jar")) {
            try {
                // Resolve the path of the jar file and load the resources from there
                Path jarFile = Paths.get(toURI(((JarURLConnection) location.openConnection()).getJarFileURL()));

                // Load the resources from the jar file
                FileSystem jarFS = FileSystems.newFileSystem(jarFile, null);
                resourcePaths.add(jarFS.getPath(resourcePath));
                jarFileSystems.add(jarFS);
            } catch (IOException e) {
                if (throwAll) {
                    throw e;
                } else {
                    LOGGER.error("Cannot read resource '{}' from jar file '{}'", resourcePath, location, e);
                }
            }
        } else {
            // Directly load the resources from the main file system
            resourcePaths.add(Paths.get(toURI(location)));
        }
    }
}

From source file:com.quartercode.femtoweb.api.resolutions.View.java

/**
 * Creates a new view action which displays the dynamic resource located under the path provided by the given components.
 * This method takes the {@link Context#getUri(Class) URI of the given action class} and replaces its last entry (the class name of the action) with the given name.
 * That means that the final path uses the URI "directory" of the given action and the given resource file name.
 * For example, calling this method with the {@link Action} class {@code test.package.SomeTestAction} and the file name {@code testForm.jsp} would result in the
 * dynamic resource path {@code /test/package/testForm.jsp}.<br>
 * <br>/*from  w w w  . jav  a2 s. c  o m*/
 * Note that the final path is relative to the {@link Context#getDynamicAssetPath() dynamic asset path}.
 *
 * @param dir The action class whose URI "directory" should be used as the directory of the final file path.
 * @param name The name of the viewed file in the directory defined by the given action class.
 */
public View(Class<? extends Action> dir, String name) {

    Validate.notNull(dir, "Cannot use null action as \"directory\" for the forwarding path");
    Validate.notBlank(name, "Cannot forward to a file with blank name");

    path = null;

    this.dir = dir;
    this.name = StringUtils.stripStart(name, "/");
}

From source file:com.nike.cerberus.service.S3StoreService.java

public List<String> listKeysInPartialPath(String path) {
    ObjectListing objectListing = s3Client.listObjects(s3Bucket, getFullPath(path));

    List<String> s3PathKeys = objectListing.getObjectSummaries().stream()
            .map(objectSummary -> StringUtils.stripStart(objectSummary.getKey(), s3Prefix + "/"))
            .collect(Collectors.toList());
    return Collections.unmodifiableList(s3PathKeys);
}

From source file:com.devbliss.risotto.RisottoParser.java

private String getContent(RisottoRISContentService content) throws IOException {
    // get content
    String line = StringUtils.stripStart(content.getNextLine(), null);
    if (line.length() < 7) {
        return "";
    }//from  w ww  .  j a v a2  s  .  co m

    String fieldContent = line.substring(6);

    // peek next line for continued infos
    while (content.hasNextLine()) {
        String nextLine = content.peekNextLine();

        // if yes, getLine and peek another line
        if (PATTERN_ITEMEXTENSION.matcher(nextLine).matches()) {
            fieldContent = fieldContent + nextLine.substring(6);
            content.skipNextLine();
        } else {
            break;
        }
    }

    return fieldContent;
}

From source file:net.dataforte.commons.resources.ClassUtils.java

private static String joinParts(String separator, String... paths) {
    Vector<String> trimmed = new Vector<String>();
    int pos = 0;//from   ww  w .  j ava 2  s  .  co m
    int last = paths.length - 1;
    for (String path : paths) {
        String trimmedPath;
        if (pos == 0)
            trimmedPath = StringUtils.stripEnd(path, separator);
        else if (pos == last)
            trimmedPath = StringUtils.stripStart(path, separator);
        else
            trimmedPath = StringUtils.strip(path, separator);
        trimmed.add(trimmedPath);
        pos += 1;
    }
    String joined = String.join(separator, trimmed);
    return joined;
}

From source file:com.quartercode.femtoweb.api.resolutions.View.java

@Override
public Action execute(HttpServletRequest request, HttpServletResponse response, Context context)
        throws IOException, ServletException {

    // Generate the actual target path (depending on the invoked constructor, use the set path or combine the "directory" URI of the set action's URI with the set name)
    String actualPath;//from  w  w w.j  ava2 s . c  om
    if (path != null) {
        actualPath = path;
    } else {
        String dirUri = StringUtils.substringBeforeLast(context.getUri(dir), "/");
        actualPath = dirUri + "/" + name;
    }

    // Add the path prefix to the directory containing dynamic content
    actualPath = context.getDynamicAssetPath() + "/" + StringUtils.stripStart(actualPath, "/");

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Forwarding request to '{}' to '{}'", RequestUtils.getRequestUri(request), actualPath);
    }

    // Actually forward the request
    request.getRequestDispatcher(actualPath).forward(request, response);

    return null;
}

From source file:com.hybris.mobile.factory.barcode.IntentBarcodeFactory.java

/**
 * Return the product value if the barcode value matches one of the pre-configured regular expression
 * /*  w  w w .j  a  v a  2  s.  c om*/
 * @param barcodeValue
 * @param barcodeSymbology
 * @return
 */
private static String getProductCode(String barcodeValue, String barcodeSymbology) {

    // For product codes, we have to remove the leading/trailing 0 of specific barcode symbologies

    // These barcodes have leading '0's and a trailing '0' that needs to be accounted for (stripped out).
    if (StringUtils.equals(barcodeSymbology, BarCodeSymbologyEnums.EAN_13.getCodeSymbology())) {
        barcodeValue = StringUtils.stripStart(barcodeValue, "0");
        barcodeValue = StringUtils.removeEnd(barcodeValue, "0");
    }
    // These barcodes have leading '0's that needs to be accounted for (stripped out).
    else if (StringUtils.equals(barcodeSymbology, BarCodeSymbologyEnums.ITF.getCodeSymbology())) {
        barcodeValue = StringUtils.stripStart(barcodeValue, "0");
    }
    // These barcodes have a trailing '0' that needs to be accounted for (stripped out).
    else if (StringUtils.equals(barcodeSymbology, BarCodeSymbologyEnums.EAN_8.getCodeSymbology())) {
        barcodeValue = StringUtils.removeEnd(barcodeValue, "0");
    }

    // Trying to get a product code from the barcode value
    return RegexUtil.getProductCode(barcodeValue);

}

From source file:com.devbliss.risotto.RisottoParser.java

private String getFieldName(RisottoRISContentService content) throws IOException {
    // get FieldName
    String line = StringUtils.stripStart(content.peekNextLine(), null);
    return line.substring(0, 2);
}

From source file:com.espe.distribuidas.pmaldito.sa.servidoraplicaciones.HiloServer.java

@Override
public void run() {
    try {//  w  w  w.j av a 2  s .  co m
        input = new DataInputStream(socket.getInputStream());
        output = new DataOutputStream(socket.getOutputStream());
        this.id = HiloServer.idGlobal++;
        System.out.println("Conexion Establecida: " + this.idGlobal);
    } catch (IOException ex) {
        Logger.getLogger(HiloServer.class.getName()).log(Level.SEVERE, null, ex);
    }

    while (true) {
        try {
            System.out.println("Esperando datos.....");
            String trama = input.readUTF();
            System.out.println("Datos recibidos.....");
            System.out.println("trama:" + trama);
            if (trama.equals("FIN")) {
                break;
            }
            String idMensaje = trama.substring(39, 49);
            System.out.println(idMensaje);

            switch (idMensaje) {
            case Mensaje.AUTENTIC_USER:
                if (trama.length() == 105 && Mensaje.validaHash(trama)) {
                    String usuario = trama.substring(85, 95);
                    String clave = trama.substring(95, 105);
                    usuario = StringUtils.stripEnd(usuario, " ");
                    clave = StringUtils.stripEnd(clave, " ");
                    AutenticacionRQ auRQ = new AutenticacionRQ();
                    auRQ.setUsuario(usuario);
                    auRQ.setClave(clave);
                    MensajeRQ mauRQ = new MensajeRQ(Originador.getOriginador(Originador.SRV_APLICACION),
                            MensajeBDD.idMensajeAutenticacion);
                    mauRQ.setCuerpo(auRQ);
                    System.out.println("TramaAutenticacion " + mauRQ.asTexto());

                    ServBase comunicacion = new ServBase();
                    comunicacion.conexion();
                    comunicacion.flujo(mauRQ.asTexto());

                    String respuesta = comunicacion.flujoRS();
                    AutenticacionRS aurs = new AutenticacionRS();
                    aurs.build(respuesta);
                    MensajeRS maurs = new MensajeRS(Originador.getOriginador(Originador.SRV_APLICACION),
                            Mensaje.AUTENTIC_USER);
                    maurs.setCuerpo(aurs);
                    output.writeUTF(maurs.asTexto());
                    System.out.println("Respuesta: " + maurs.asTexto());
                }
                break;
            case Mensaje.INFO_CLIENT:
                if (Mensaje.validaHash(trama)) {
                    String idCliente = trama.substring(85);
                    idCliente = StringUtils.stripStart(idCliente, "0");
                    System.out.println("Id_Cliente:" + idCliente);
                    ConsultarRQ coninfCli = new ConsultarRQ();
                    coninfCli.setNombreTabla(Mensaje.nombreTablaCliente);
                    coninfCli.setCamposTabla("/");
                    coninfCli.setCodigoIdentificadorColumna("1");
                    coninfCli.setValorCodigoidentificadorColumna(idCliente);
                    MensajeRQ mconinfCli = new MensajeRQ(Originador.getOriginador(Originador.SRV_APLICACION),
                            MensajeBDD.idMensajeConsultar);
                    mconinfCli.setCuerpo(coninfCli);
                    System.out.println("Trama Info CLiente " + mconinfCli.asTexto());

                    ServBase comunicacion = new ServBase();
                    comunicacion.conexion();
                    comunicacion.flujo(mconinfCli.asTexto());

                    String respuesta = comunicacion.flujoRS();
                    InformacionClienteRS infclRS = new InformacionClienteRS();
                    infclRS.build(respuesta);
                    MensajeRS minfclRS = new MensajeRS(Originador.getOriginador(Originador.SRV_APLICACION),
                            Mensaje.INFO_CLIENT);
                    minfclRS.setCuerpo(infclRS);

                    output.writeUTF(minfclRS.asTexto());
                    System.out.println("RespuestaInfCliente: " + minfclRS.asTexto());
                }
                break;
            case Mensaje.INFO_FACT:

                break;
            case Mensaje.INFO_PRODUCT:
                if (Mensaje.validaHash(trama)) {
                    String idProducto = trama.substring(85);
                    idProducto = StringUtils.stripEnd(idProducto, " ");
                    System.out.println("Id_Producto:" + idProducto);
                    ConsultarRQ infoPro = new ConsultarRQ();
                    infoPro.setNombreTabla(Mensaje.nombreTablaProducto);
                    infoPro.setCamposTabla("/");
                    infoPro.setCodigoIdentificadorColumna("0");
                    infoPro.setValorCodigoidentificadorColumna(idProducto);
                    MensajeRQ mconinfCli = new MensajeRQ(Originador.getOriginador(Originador.SRV_APLICACION),
                            MensajeBDD.idMensajeConsultar);
                    mconinfCli.setCuerpo(infoPro);
                    System.out.println("Trama Info Producto " + mconinfCli.asTexto());

                    ServBase comunicacion = new ServBase();
                    comunicacion.conexion();
                    comunicacion.flujo(mconinfCli.asTexto());

                    String respuesta = comunicacion.flujoRS();
                    InformacionProductoRS infoProRS = new InformacionProductoRS();
                    infoProRS.build(respuesta);
                    MensajeRS minfoProRS = new MensajeRS(Originador.getOriginador(Originador.SRV_APLICACION),
                            Mensaje.INFO_PRODUCT);
                    minfoProRS.setCuerpo(infoProRS);

                    output.writeUTF(minfoProRS.asTexto());
                    System.out.println("RespuestaInfCliente: " + minfoProRS.asTexto());
                }
                break;
            case Mensaje.INSERT_CLIENT:
                if (Mensaje.validaHash(trama)) {
                    String cuerpo = trama.substring(85);
                    InsertarRQ inserRQ = new InsertarRQ();
                    inserRQ.setNombreTabla(Mensaje.nombreTablaCliente);
                    inserRQ.setValorCamposTabla(cuerpo);
                    MensajeRQ minserRQ = new MensajeRQ(Originador.getOriginador(Originador.SRV_APLICACION),
                            MensajeBDD.idMensajeInsertar);
                    minserRQ.setCuerpo(inserRQ);
                    System.out.println("TramaInsertarFactura " + minserRQ.asTexto());

                    ServBase comunicacion = new ServBase();
                    comunicacion.conexion();
                    comunicacion.flujo(minserRQ.asTexto());

                    String respuesta = comunicacion.flujoRS();
                    IngresarClienteRS incRS = new IngresarClienteRS();
                    incRS.build(respuesta);
                    MensajeRS mincRS = new MensajeRS(Originador.getOriginador(Originador.SRV_APLICACION),
                            Mensaje.INSERT_CLIENT);
                    mincRS.setCuerpo(incRS);
                    output.writeUTF(mincRS.asTexto());
                    System.out.println("Respuesta: " + mincRS.asTexto());

                }
                break;
            case Mensaje.INSERT_FACT:
                if (Mensaje.validaHash(trama)) {
                    String cuerpo = trama.substring(85);
                    InsertarRQ inserRQ = new InsertarRQ();
                    inserRQ.setNombreTabla(Mensaje.nombreTablaFactura);
                    inserRQ.setValorCamposTabla(cuerpo);
                    MensajeRQ minserRQ = new MensajeRQ(Originador.getOriginador(Originador.SRV_APLICACION),
                            MensajeBDD.idMensajeInsertar);
                    minserRQ.setCuerpo(inserRQ);
                    System.out.println("TramaInsertarCliente " + minserRQ.asTexto());

                    ServBase comunicacion = new ServBase();
                    comunicacion.conexion();
                    comunicacion.flujo(minserRQ.asTexto());
                    String respuesta = comunicacion.flujoRS();
                    IngresarFacturaRS incRS = new IngresarFacturaRS();
                    incRS.build(respuesta);
                    MensajeRS mincRS = new MensajeRS(Originador.getOriginador(Originador.SRV_APLICACION),
                            Mensaje.INSERT_FACT);
                    mincRS.setCuerpo(incRS);
                    output.writeUTF(mincRS.asTexto());
                    System.out.println("Respuesta: " + mincRS.asTexto());
                }
                break;

            }

        } catch (IOException ex) {
            Logger.getLogger(HiloServer.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("no se pudo recibir la trama");
            break;
        }

    }
}