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

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

Introduction

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

Prototype

public static String removeStart(String str, String remove) 

Source Link

Document

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

Usage

From source file:org.ovirt.engine.api.utils.LinkCreator.java

/**
 * Combine head and tail portions of a URI path.
 *
 * @param head the path head//from  w w w.j a v a2 s.c  om
 * @param tail the path tail
 * @return the combined head and tail
 */
public static String combine(String head, String tail) {
    return StringUtils.removeEnd(head, "/") + "/" + StringUtils.removeStart(tail, "/");
}

From source file:org.pepstock.jem.jbpm.tasks.ValueParser.java

/**
 * Parses the value of variables in JBPM and loads datasets into data descriptions
 * @param dd data description to load/*from  ww w. j  a va  2s  .c o  m*/
 * @param valueParm value of assignment in BPMN2 language
 * @throws JBpmException if any error occurs
 */
public static final void loadDataDescription(DataDescription dd, String valueParm) throws JBpmException {
    // trim value
    String value = valueParm.trim();

    // init of variables to load dd
    String[] dsn = null;
    String disposition = null;
    String dataSource = null;
    boolean isSysout = false;
    // this boolean is set to true 
    // because if it's not able to parse the content,
    // the wjole string will be the content of dataset
    boolean isText = true;

    // parses using comma
    String[] stmtTokens = StringUtils.split(value, COMMAND_SEPARATOR);
    if (stmtTokens != null && stmtTokens.length > 0) {
        // scans all tokes
        for (int i = 0; i < stmtTokens.length; i++) {
            String token = stmtTokens[i].trim();
            // is datasetname?
            if (StringUtils.startsWithIgnoreCase(token, DSN_PREFIX)) {
                // gets all string after DSN and =
                String subToken = getValue(token, DSN_PREFIX);
                if (subToken != null) {
                    // sets that is not a text
                    isText = false;

                    String subValue = null;
                    // checks if the content is inside of brackets
                    if (subToken.startsWith("(") && subToken.endsWith(")")) {
                        // gets content inside brackets
                        subValue = StringUtils.removeEnd(StringUtils.removeStart(subToken, "("), ")");
                    } else {
                        // only 1 datasets
                        subValue = subToken;
                    }
                    // parses values
                    dsn = StringUtils.split(subValue, VALUE_SEPARATOR);
                }
            } else if (StringUtils.startsWithIgnoreCase(token, DISP_PREFIX)) {
                // sets that is not a text
                isText = false;
                // saves disposition
                disposition = getValue(token, DISP_PREFIX);
            } else if (StringUtils.startsWithIgnoreCase(token, DATASOURCE_PREFIX)) {
                // sets that is not a text
                isText = false;
                // saves data sourceinfo
                dataSource = getValue(token, DATASOURCE_PREFIX);
            } else if (StringUtils.startsWithIgnoreCase(token, SYSOUT)) {
                // sets that is not a text
                isText = false;
                // sets is a sysout
                isSysout = true;
            }
        }
    }
    // content of file
    if (isText) {
        dd.setDisposition(Disposition.SHR);
        DataSet ds = createDataSet(dd, null, valueParm);
        dd.addDataSet(ds);
    } else {
        // disposition DISP= is mandatory, always
        if (disposition == null) {
            throw new JBpmException(JBpmMessage.JEMM050E, dd.getName());
        }
        dd.setDisposition(disposition);

        // if sets SYSOUT but also DSN=, this is not allowed
        if (isSysout && dsn != null) {
            throw new JBpmException(JBpmMessage.JEMM051E, dd.getName());
        }
        // sets sysout
        dd.setSysout(isSysout);
        // if not sysout, loads datasets
        // datasource can be set ONLY with 1 dataset
        if (!isSysout && dsn != null) {
            if (dsn.length > 1 && dataSource != null) {
                throw new JBpmException(JBpmMessage.JEMM052E, dd.getName());
            }
            // loads all datasets and set datasource
            for (int k = 0; k < dsn.length; k++) {
                DataSet ds = createDataSet(dd, dsn[k], null);
                dd.addDataSet(ds);
                // doesn't check anything because
                // already done before
                if (dataSource != null) {
                    ds.setDatasource(dataSource);
                }
            }
        }
    }
}

From source file:org.pepstock.jem.jbpm.tasks.ValueParser.java

/**
 * Parses the value of variable in JBPM and load all data source properties if there are
 * @param ds data source to be loaded/*from  w ww.j av  a  2  s  .  co m*/
 * @param valueParm value specified on JBPM xml assignment
 * @throws JBpmException if any error occurs
 */
public static final void loadDataSource(DataSource ds, String valueParm) throws JBpmException {
    // trim value
    String value = valueParm.trim();

    // parses using comma
    String[] stmtTokens = StringUtils.split(value, COMMAND_SEPARATOR);
    if (stmtTokens != null && stmtTokens.length > 0) {
        // scans all tokes
        for (int i = 0; i < stmtTokens.length; i++) {
            String token = stmtTokens[i].trim();
            // is datasetname?
            if (StringUtils.startsWithIgnoreCase(token, PROPERTIES_PREFIX)) {
                // gets all string after DSN=
                String subToken = getValue(token, PROPERTIES_PREFIX);
                if (subToken.startsWith("(") && subToken.endsWith(")")) {
                    // gets content inside brackets
                    String subValue = StringUtils.removeEnd(StringUtils.removeStart(subToken, "("), ")");
                    // if subvalue is null, exception
                    if (subValue != null) {
                        // changes all ; in line separator because by areader it can load a properties object
                        subValue = subValue.replace(VALUE_SEPARATOR, System.getProperty("line.separator"))
                                .concat(System.getProperty("line.separator"));
                        // loads all properties from a reader
                        StringReader reader = new StringReader(subValue);
                        Properties properties = new Properties();
                        try {
                            // loads it
                            properties.load(reader);
                            // scans all properties to creates property object
                            for (Entry<Object, Object> entry : properties.entrySet()) {
                                // creates properties
                                Property prop = new Property();
                                prop.setName(entry.getKey().toString());
                                prop.addText(entry.getValue().toString());
                                ds.addProperty(prop);
                            }
                        } catch (IOException e) {
                            LogAppl.getInstance().ignore(e.getMessage(), e);
                        }
                    } else {
                        throw new JBpmException(JBpmMessage.JEMM054E, ds.getName());
                    }
                } else {
                    throw new JBpmException(JBpmMessage.JEMM054E, ds.getName());
                }
            } else if (StringUtils.startsWithIgnoreCase(token, RESOURCE_PREFIX)) {
                String subToken = getValue(token, RESOURCE_PREFIX);
                // sets that is not a text
                ds.setResource(subToken);
            }
        }
    }
}

From source file:org.polymap.core.mapeditor.RenderManager.java

/**
 * Prepares the render pipelines / OwsServers for the map.
 * <ol>/*from  w w w .j  a v  a 2 s .c  o m*/
 * <li>find the {@link IService}s that are associated with the layers of the {@link #map}.</li>
 * <li>create a render pipeline for each service.<li>
 * <li>create a {@link WmsService} server for each service/pipeline.</li>
 * </ol>
 * @throws Exception 
 */
protected synchronized void updatePipelines() {
    clearPipelines();
    IProgressMonitor monitor = UIJob.monitorForThread();

    if (wmsServer != null) {
        destroyWms(wmsServer);
        wmsServer = null;
    }
    wmsServer = createWms();

    // check geoResource of layers
    for (final ILayer layer : map.getLayers()) {
        try {
            log.debug("layer: " + layer + ", label= " + layer.getLabel() + ", visible= " + layer.isVisible());
            if (layer.isVisible()) {
                monitor.subTask(i18n.get("georesTaskTitle", layer.getLabel()));
                IGeoResource res = layer.getGeoResource();
                if (res == null) {
                    log.warn("Unable to find geo resource of layer: " + layer);
                    Display.getCurrent().asyncExec(new Runnable() {
                        public void run() {
                            IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
                            MessageBox box = new MessageBox(window.getShell(),
                                    SWT.APPLICATION_MODAL | SWT.ICON_WARNING);
                            String label = layer instanceof LayerComposite
                                    ? ((LayerComposite) layer).georesId().get()
                                    : layer.getLabel();
                            box.setMessage(i18n.get("noGeoresMsg", label));
                            box.setText(i18n.get("noGeoresTitle", label));
                            box.open();
                        }
                    });
                    continue;
                }

                RenderLayerDescriptor descriptor = new RenderLayerDescriptor(
                        StringUtils.removeStart(wmsServer.getPathSpec(), "/"), layer.getOrderKey(),
                        layer.getOpacity());
                descriptor.layer = layer;
                boolean added = descriptors.add(descriptor);
                assert added : "Unable to add layer descriptor: " + descriptor.layerNames();

                monitor.worked(1);
            }
        } catch (Exception e) {
            // XXX mark layers!?
            log.warn("skipping layer: " + layer.getLabel() + " (" + e.toString(), e);
        }
    }

    // add layers to mapEditor
    for (RenderLayerDescriptor descriptor : descriptors) {
        mapEditor.addLayer(descriptor);
    }
}

From source file:org.polymap.core.mapeditor.services.JsonVectorLayer.java

public JsonVectorLayer(String name, SimpleJsonServer jsonServer, JsonEncoder jsonEncoder, StyleMap styleMap) {
    super(name, new Protocol(Protocol.TYPE.HTTP,
            StringUtils.removeStart(jsonServer.getPathSpec(), "/") + "/" + jsonEncoder.getName(), "GeoJSON"),
            styleMap);//from   www.  j a  va2 s .  com
    this.jsonEncoder = jsonEncoder;
    this.jsonServer = jsonServer;

    // init phase listener: prevent subsequent refreshs if just created
    RWT.getLifeCycle().addPhaseListener(phaseListener = new PhaseListener() {
        @Override
        public PhaseId getPhaseId() {
            return PhaseId.RENDER;
        }

        @Override
        public void beforePhase(PhaseEvent event) {
        }

        @Override
        public void afterPhase(PhaseEvent event) {
            log.info("AFTER PHASE: " + getName());
            phaseListener = null;
            RWT.getLifeCycle().removePhaseListener(this);
        }
    });

    log.debug("URL: " + jsonServer.getPathSpec() + "/" + jsonEncoder.getName());
}

From source file:org.polymap.core.style.StylePlugin.java

public String getServletPathForId(ID id) {
    servlet_path_mapping.put(id.labelResource(), id);
    return StringUtils.removeStart(sld_servlet_path, "/") + "/" + id.labelResource();
}

From source file:org.rapidcontext.app.web.AppWebService.java

/**
 * Finds binary files of a specified type from the storage. The
 * file type is both used as a subdirectory (i.e. "files/css")
 * and as a suffix (i.e. "*.css") when performing the search. The
 * returned files will be prefixed with the proper path (e.g.
 * "rapidcontext/files/") relative to the specified base path for
 * the web service. The current platform version will be added as
 * a parameter to the file URL:s./*from  w  w w  .java 2 s .c om*/
 *
 * @param type           the file type to find
 * @param base           the web service root path
 *
 * @return a sorted list of all matching files found in storage
 */
protected static ArrayList resources(String type, Path base) {
    ArrayList res = new ArrayList();
    ApplicationContext ctx = ApplicationContext.getInstance();
    Path storagePath = new Path(PATH_FILES, type + "/");
    Metadata[] meta = ctx.getStorage().lookupAll(storagePath);
    String rootPath = PATH_FILES.toString();
    String basePath = base.toString();
    String ver = version();
    for (int i = 0; i < meta.length; i++) {
        String file = meta[i].path().toString();
        if (meta[i].isBinary() && file.endsWith("." + type)) {
            if (file.startsWith(basePath)) {
                file = StringUtils.removeStart(file, basePath);
            } else {
                file = StringUtils.removeStart(file, rootPath);
                file = "rapidcontext/files/" + file;
            }
            res.add(file + "?" + ver);
        }
    }
    Collections.sort(res);
    return res;
}

From source file:org.rapidcontext.app.web.AppWebService.java

/**
 * Processes an HTML template file for a app and returns the text.
 *
 * @param template       the template file to read
 * @param baseUrl        the base URL for requests
 * @param appId          the app identifier, or null for 'start'
 *
 * @return the processed contents of the HTML template file
 *
 * @throws IOException if the template file couldn't be read
 *//* ww  w . j av a2 s . co  m*/
protected String processAppTemplate(Binary template, String baseUrl, String appId) throws IOException {

    InputStreamReader is = new InputStreamReader(template.openStream(), "UTF-8");
    BufferedReader reader = new BufferedReader(is);
    StringBuilder res = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        // Simple text replacement
        if (line.contains("%APP_ID%")) {
            if (appId == null || appId.equals("")) {
                line = line.replace("%APP_ID%", "null");
            } else {
                line = line.replace("%APP_ID%", "'" + appId + "'");
            }
        }
        if (line.contains("%TITLE%")) {
            line = line.replace("%TITLE%", title());
        }
        if (line.contains("%LANG%")) {
            line = line.replace("%LANG%", lang());
        }
        if (line.contains("%VIEWPORT%")) {
            line = line.replace("%VIEWPORT%", viewport());
        }
        if (line.contains("%BASE_URL%")) {
            line = line.replace("%BASE_URL%", baseUrl);
        }
        if (line.contains("%BASE_PATH%")) {
            if (PATH_FILES.equals(path())) {
                // Skip this line, no config needed
                continue;
            }
            String str = StringUtils.removeStart(path().toString(), PATH_FILES.toString());
            line = line.replace("%BASE_PATH%", str);
        }
        // Complex text replacement & printout
        if (line.contains("%HEADER%")) {
            ArrayList headers = headerLines();
            for (int i = 0; i < headers.size(); i++) {
                String str = (String) headers.get(i);
                res.append(line.replace("%HEADER%", str));
                res.append("\n");
            }
        } else if (line.contains("%JS_FILES%")) {
            ArrayList files = resources("js", path());
            for (int i = 0; i < files.size(); i++) {
                String str = (String) files.get(i);
                res.append(line.replace("%JS_FILES%", str));
                res.append("\n");
            }
        } else if (line.contains("%CSS_FILES%")) {
            ArrayList files = resources("css", path());
            for (int i = 0; i < files.size(); i++) {
                String str = (String) files.get(i);
                res.append(line.replace("%CSS_FILES%", str));
                res.append("\n");
            }
        } else {
            res.append(line);
            res.append("\n");
        }
    }
    reader.close();
    return res.toString();
}

From source file:org.rapidcontext.core.security.SecurityContext.java

/**
 * Checks if the specified user has has access permission for a
 * storage path.//from w  ww.  jav a 2s. c om
 *
 * @param user           the user to check, or null or anonymous
 * @param path           the object storage path
 * @param permission     the requested permission
 *
 * @return true if the current user has access, or
 *         false otherwise
 *
 * @see Role#hasAccess(String, String)
 */
public static boolean hasAccess(User user, String path, String permission) {
    path = StringUtils.removeStart(path, "/");
    permission = permission.toLowerCase().trim();
    for (int i = 0; i < roleCache.length; i++) {
        Role role = roleCache[i];
        if (role.hasUser(user) && role.hasAccess(path, permission)) {
            return true;
        }
    }
    return false;
}

From source file:org.rapidcontext.core.type.Environment.java

/**
 * Returns the default connection path for this environment.
 *
 * @return the default connection path for this environment
 *//*from w w w .java 2 s. co m*/
public String connectionPath() {
    String prefix;

    prefix = dict.getString(KEY_CONNECTIONS, null);
    if (prefix != null) {
        prefix = StringUtils.removeStart(prefix, "/");
        if (!prefix.endsWith("/")) {
            prefix += "/";
        }
    }
    return prefix;
}