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.joyent.manta.http.HttpRange.java

/**
 * Deserialize a request range.//from   ww  w  . ja va 2s . c  om
 *
 * @param requestRange the string representation of the range
 * @return a {@link BoundedRequest} range
 * @throws ProtocolException if the range could not be parsed
 */
static Request parseRequestRange(final String requestRange) throws ProtocolException {
    notNull(requestRange, "Request Range must not be null");

    final boolean boundedMatch = requestRange.matches(REGEX_BOUNDED_REQUEST_RANGE);
    final boolean unboundedMatch = requestRange.matches(REGEX_UNBOUNDED_REQUEST_RANGE);
    if (!boundedMatch && !unboundedMatch) {
        throw new ProtocolException(String.format(FMT_ERROR_MATCHING_REQUEST_RANGE, requestRange));
    }

    final String[] bounds = StringUtils.split(StringUtils.removeStart(requestRange, "bytes="), "-");
    if (boundedMatch) {
        if (bounds.length != PART_COUNT_BOUNDED_RANGE) {
            throw new ProtocolException(String.format(FMT_ERROR_MATCHING_REQUEST_RANGE, requestRange));
        }

        return new BoundedRequest(Long.parseUnsignedLong(bounds[0]), Long.parseUnsignedLong(bounds[1]));
    }

    if (unboundedMatch && bounds.length != PART_COUNT_UNBOUNDED_RANGE) {
        throw new ProtocolException(String.format(FMT_ERROR_MATCHING_REQUEST_RANGE, requestRange));
    }

    return new UnboundedRequest(Long.parseUnsignedLong(bounds[0]));
}

From source file:gobblin.data.management.copy.hive.HiveDataset.java

/***
 * Extract token value from source entity, where token value is represented by a token in the source entity.
 *
 * Eg./*from  ww  w . ja v a 2 s  . c o  m*/
 * Source Entity  : prod_tableName_avro
 * Source Template: prod_$LOGICAL_TABLE_avro
 * Token          : $LOGICAL_TABLE
 * Extracted Value: tableName
 *
 * @param sourceEntity      Source entity (typically a table or database name).
 * @param sourceTemplate    Source template representing the source entity.
 * @param token             Token representing the value to extract from the source entity using the template.
 * @return Extracted token value from the source entity.
 */
@VisibleForTesting
protected static String extractTokenValueFromEntity(String sourceEntity, String sourceTemplate, String token) {
    Preconditions.checkArgument(StringUtils.isNotBlank(sourceEntity), "Source entity should not be blank");
    Preconditions.checkArgument(StringUtils.isNotBlank(sourceTemplate), "Source template should not be blank");
    Preconditions.checkArgument(sourceTemplate.contains(token),
            String.format("Source template: %s should contain token: %s", sourceTemplate, token));

    String extractedValue = sourceEntity;
    List<String> preAndPostFix = Lists.newArrayList(Splitter.on(token).trimResults().split(sourceTemplate));

    extractedValue = StringUtils.removeStart(extractedValue, preAndPostFix.get(0));
    extractedValue = StringUtils.removeEnd(extractedValue, preAndPostFix.get(1));

    return extractedValue;
}

From source file:com.iorga.iraj.servlet.AgglomeratorServlet.java

private long searchAndAppendAfter(final ServletConfig config, final Element agglomerateElement,
        final String scriptSrc, final String pathPrefix, final String pathSuffix, final String urlAttribute,
        long lastModified) throws MalformedURLException, IOException, URISyntaxException {
    if (mode == Mode.DEVELOPMENT) {
        // add a watch for that directory
        final Path path = Paths.get(config.getServletContext().getRealPath(scriptSrc));
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
    }// w  ww.  ja  v  a  2 s  . c o  m
    final Set<String> childrenPaths = config.getServletContext().getResourcePaths(scriptSrc);
    for (final String path : childrenPaths) {
        if (path.endsWith(pathSuffix)) {
            // add that JS
            final StringBuilder targetScript = new StringBuilder("<");
            targetScript.append(agglomerateElement.tagName());
            // copy all the origin attributes
            for (final Attribute attribute : agglomerateElement.attributes()) {
                final String key = attribute.getKey();
                if (!ATTRIBUTE_NAME.equalsIgnoreCase(key) && !urlAttribute.equalsIgnoreCase(key)
                        && !URL_ATTRIBUTE_ATTRIBUTE_NAME.equalsIgnoreCase(key)) {
                    targetScript.append(" ").append(attribute.html());
                }
            }
            // specify the src path
            final String childUrl = StringUtils.removeStart(path, pathPrefix);
            targetScript.append(" ").append(new Attribute(urlAttribute, childUrl).html()).append(" />");
            agglomerateElement.after(targetScript.toString());
            lastModified = Math.max(
                    config.getServletContext().getResource(childUrl).openConnection().getLastModified(),
                    lastModified);
        } else if (path.endsWith("/")) {
            // it's a directory, recurse search & append
            lastModified = Math.max(searchAndAppendAfter(config, agglomerateElement, path, pathPrefix,
                    pathSuffix, urlAttribute, lastModified), lastModified);
        }
    }
    return lastModified;
}

From source file:com.bellman.bible.service.device.speak.TextToSpeechController.java

@Override
public void onUtteranceCompleted(String utteranceId) {
    Log.d(TAG, "onUtteranceCompleted:" + utteranceId);
    // pause/rew/ff can sometimes allow old messages to complete so need to prevent move to next sentence if completed utterance is out of date
    if ((!isPaused && isSpeaking) && StringUtils.startsWith(utteranceId, UTTERANCE_PREFIX)) {
        long utteranceNo = Long.valueOf(StringUtils.removeStart(utteranceId, UTTERANCE_PREFIX));
        if (utteranceNo == uniqueUtteranceNo - 1) {
            mSpeakTextProvider.finishedUtterance(utteranceId);

            // estimate cps
            mSpeakTiming.finished(utteranceId);

            // ask TTs to say the text
            if (mSpeakTextProvider.isMoreTextToSpeak()) {
                speakNextChunk();/*from   www .j  a v a  2s  .  c  o  m*/
            } else {
                Log.d(TAG, "Shutting down TTS");
                shutdown();
            }
        }
    }
}

From source file:com.technophobia.substeps.report.DefaultExecutionReportBuilder.java

public void copyJarResourcesRecursively(final File destination, final JarURLConnection jarConnection)
        throws IOException {
    final JarFile jarFile = jarConnection.getJarFile();
    for (final JarEntry entry : Collections.list(jarFile.entries())) {
        if (entry.getName().startsWith(jarConnection.getEntryName())) {
            final String fileName = StringUtils.removeStart(entry.getName(), jarConnection.getEntryName());
            if (!entry.isDirectory()) {
                InputStream entryInputStream = null;
                try {
                    entryInputStream = jarFile.getInputStream(entry);
                    FileUtils.copyInputStreamToFile(entryInputStream, new File(destination, fileName));
                } finally {
                    IOUtils.closeQuietly(entryInputStream);
                }//w  w  w .  j a  v  a 2 s . c  o  m
            } else {
                new File(destination, fileName).mkdirs();
            }
        }
    }
}

From source file:annis.gui.SearchUI.java

@Override
protected void init(VaadinRequest request) {
    super.init(request);

    this.instanceConfig = getInstanceConfig(request);

    getPage().setTitle(instanceConfig.getInstanceDisplayName() + " (ANNIS Corpus Search)");

    queryController = new QueryController(this);

    refresh = new Refresher();
    // deactivate refresher by default
    refresh.setRefreshInterval(-1);/*from   w  w w  .j av a 2 s. c  o m*/
    refresh.addListener(queryController);
    addExtension(refresh);

    // always get the resize events directly
    setImmediate(true);

    VerticalLayout mainLayout = new VerticalLayout();
    setContent(mainLayout);

    mainLayout.setSizeFull();
    mainLayout.setMargin(false);

    final ScreenshotMaker screenshot = new ScreenshotMaker(this);
    addExtension(screenshot);

    css = new CSSInject(this);

    HorizontalLayout layoutToolbar = new HorizontalLayout();
    layoutToolbar.setWidth("100%");
    layoutToolbar.setHeight("-1px");

    mainLayout.addComponent(layoutToolbar);
    layoutToolbar.addStyleName("toolbar");
    layoutToolbar.addStyleName("border-layout");

    Button btAboutAnnis = new Button("About ANNIS");
    btAboutAnnis.addStyleName(ChameleonTheme.BUTTON_SMALL);
    btAboutAnnis.setIcon(new ThemeResource("info.gif"));

    btAboutAnnis.addClickListener(new AboutClickListener());

    btBugReport = new Button("Report Bug");
    btBugReport.addStyleName(ChameleonTheme.BUTTON_SMALL);
    btBugReport.setDisableOnClick(true);
    btBugReport.setIcon(new ThemeResource("../runo/icons/16/email.png"));
    btBugReport.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            screenshot.makeScreenshot();
            btBugReport.setCaption("bug report is initialized...");
        }
    });

    String bugmail = (String) VaadinSession.getCurrent().getAttribute("bug-e-mail");
    if (bugmail != null && !bugmail.isEmpty() && !bugmail.startsWith("${")
            && new EmailValidator("").isValid(bugmail)) {
        this.bugEMailAddress = bugmail;
    }
    btBugReport.setVisible(this.bugEMailAddress != null);

    lblUserName = new Label("not logged in");
    lblUserName.setWidth("-1px");
    lblUserName.setHeight("-1px");
    lblUserName.addStyleName("right-aligned-text");

    btLoginLogout = new Button("Login", new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            if (isLoggedIn()) {
                // logout
                Helper.setUser(null);
                Notification.show("Logged out", Notification.Type.TRAY_NOTIFICATION);
                updateUserInformation();
            } else {
                showLoginWindow();
            }
        }
    });
    btLoginLogout.setSizeUndefined();
    btLoginLogout.setStyleName(ChameleonTheme.BUTTON_SMALL);
    btLoginLogout.setIcon(new ThemeResource("../runo/icons/16/user.png"));

    Button btOpenSource = new Button("Help us to make ANNIS better!");
    btOpenSource.setStyleName(BaseTheme.BUTTON_LINK);
    btOpenSource.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            Window w = new HelpUsWindow();
            w.setCaption("Help us to make ANNIS better!");
            w.setModal(true);
            w.setResizable(true);
            w.setWidth("600px");
            w.setHeight("500px");
            addWindow(w);
            w.center();
        }
    });

    layoutToolbar.addComponent(btAboutAnnis);
    layoutToolbar.addComponent(btBugReport);
    layoutToolbar.addComponent(btOpenSource);
    layoutToolbar.addComponent(lblUserName);
    layoutToolbar.addComponent(btLoginLogout);

    layoutToolbar.setSpacing(true);
    layoutToolbar.setComponentAlignment(btAboutAnnis, Alignment.MIDDLE_LEFT);
    layoutToolbar.setComponentAlignment(btBugReport, Alignment.MIDDLE_LEFT);
    layoutToolbar.setComponentAlignment(btOpenSource, Alignment.MIDDLE_CENTER);
    layoutToolbar.setComponentAlignment(lblUserName, Alignment.MIDDLE_RIGHT);
    layoutToolbar.setComponentAlignment(btLoginLogout, Alignment.MIDDLE_RIGHT);
    layoutToolbar.setExpandRatio(btOpenSource, 1.0f);

    //HorizontalLayout hLayout = new HorizontalLayout();
    final HorizontalSplitPanel hSplit = new HorizontalSplitPanel();
    hSplit.setSizeFull();

    mainLayout.addComponent(hSplit);
    mainLayout.setExpandRatio(hSplit, 1.0f);

    AutoGeneratedQueries autoGenQueries = new AutoGeneratedQueries("example queries", this);

    controlPanel = new ControlPanel(queryController, instanceConfig, autoGenQueries);
    controlPanel.setWidth(100f, Layout.Unit.PERCENTAGE);
    controlPanel.setHeight(100f, Layout.Unit.PERCENTAGE);
    hSplit.setFirstComponent(controlPanel);

    tutorial = new TutorialPanel();
    tutorial.setHeight("99%");

    mainTab = new TabSheet();
    mainTab.setSizeFull();
    mainTab.addTab(autoGenQueries, "example queries");
    mainTab.addTab(tutorial, "Tutorial");

    queryBuilder = new QueryBuilderChooser(queryController, this, instanceConfig);
    mainTab.addTab(queryBuilder, "Query Builder");

    hSplit.setSecondComponent(mainTab);
    hSplit.setSplitPosition(CONTROL_PANEL_WIDTH, Unit.PIXELS);
    hSplit.addSplitterClickListener(new AbstractSplitPanel.SplitterClickListener() {
        @Override
        public void splitterClick(AbstractSplitPanel.SplitterClickEvent event) {
            if (event.isDoubleClick()) {
                if (hSplit.getSplitPosition() == CONTROL_PANEL_WIDTH) {
                    // make small
                    hSplit.setSplitPosition(0.0f, Unit.PIXELS);
                } else {
                    // reset to default width
                    hSplit.setSplitPosition(CONTROL_PANEL_WIDTH, Unit.PIXELS);
                }
            }
        }
    });
    // hLayout.setExpandRatio(mainTab, 1.0f);

    addAction(new ShortcutListener("^Query builder") {
        @Override
        public void handleAction(Object sender, Object target) {
            mainTab.setSelectedTab(queryBuilder);
        }
    });

    addAction(new ShortcutListener("Tutor^eial") {
        @Override
        public void handleAction(Object sender, Object target) {
            mainTab.setSelectedTab(tutorial);
        }
    });

    getPage().addUriFragmentChangedListener(this);

    getSession().addRequestHandler(new RequestHandler() {
        @Override
        public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response)
                throws IOException {
            checkCitation(request);

            if (request.getPathInfo() != null && request.getPathInfo().startsWith("/vis-iframe-res/")) {
                String uuidString = StringUtils.removeStart(request.getPathInfo(), "/vis-iframe-res/");
                UUID uuid = UUID.fromString(uuidString);
                IFrameResourceMap map = VaadinSession.getCurrent().getAttribute(IFrameResourceMap.class);
                if (map == null) {
                    response.setStatus(404);
                } else {
                    IFrameResource res = map.get(uuid);
                    if (res != null) {
                        response.setStatus(200);
                        response.setContentType(res.getMimeType());
                        response.getOutputStream().write(res.getData());
                    }
                }
                return true;
            }

            return false;
        }
    });

    getSession().setAttribute(MediaController.class, new MediaControllerImpl());

    getSession().setAttribute(PDFController.class, new PDFControllerImpl());

    loadInstanceFonts();

    checkCitation(request);
    lastQueriedFragment = "";
    evaluateFragment(getPage().getUriFragment());

    updateUserInformation();
}

From source file:com.joyent.manta.http.HttpRange.java

/**
 * Deserialize a response (Content-Range) range.
 *
 * @param contentRange the string representation of the range
 * @return a {@link BoundedRequest} range
 * @throws ProtocolException if the range could not be parsed
 *//*from w w w .  jav  a  2s .co m*/
static Response parseContentRange(final String contentRange) throws ProtocolException {
    notNull(contentRange, "Content Range must not be null");

    if (!contentRange.matches(REGEX_CONTENT_RANGE)) {
        final String message = String.format("Invalid content-range format, expected: "
                + "[bytes <startInclusive>-<endInclusive>/<size>], got: %s", contentRange);
        throw new ProtocolException(message);
    }

    final String[] boundsAndSize = StringUtils.split(StringUtils.removeStart(contentRange, "bytes "), "-/");
    if (boundsAndSize.length != PART_COUNT_CONTENT_RANGE) {
        throw new ProtocolException(String.format("Malformed Range value, got: %s", contentRange));
    }

    return new Response(Long.parseUnsignedLong(boundsAndSize[0]), Long.parseUnsignedLong(boundsAndSize[1]),
            Long.parseUnsignedLong(boundsAndSize[2]));
}

From source file:com.sonicle.webtop.core.app.ServiceDescriptor.java

private String sanitizeApiEndpointPath(String serviceId, String path) {
    if (StringUtils.isBlank(path)) {
        return serviceId;
    } else {//from ww  w  .  j a v a 2 s  . c  om
        return serviceId + "/" + StringUtils.removeStart(path, "/");
    }
}

From source file:it.attocchi.utils.jdbc.QueryBuilderSqlServer.java

/**
 * ciao esegue ricerca = ciao* esegue ricerca ciao% *ciao esegue ricerca
 * %ciao *ciao* esegue ricerca %ciao%//from  w  ww  .ja  v a  2 s .c  o  m
 * 
 * @param campo
 * @param semeRicerca
 * @return
 */
public static String likeOrEquaByUser(String campo, String semeRicerca) {
    StringBuilder res = new StringBuilder();

    if (semeRicerca.startsWith(QueryBuilderSqlServer.RICERCA_JOLLY_CHAR)
            && semeRicerca.endsWith(QueryBuilderSqlServer.RICERCA_JOLLY_CHAR)) {
        /* CASO "ciao" */
        semeRicerca = StringUtils.removeStart(semeRicerca, QueryBuilderSqlServer.RICERCA_JOLLY_CHAR);
        semeRicerca = StringUtils.removeEnd(semeRicerca, QueryBuilderSqlServer.RICERCA_JOLLY_CHAR);
        res.append(campo + " LIKE '%" + encodeStringSQL(semeRicerca) + "%'");
    } else if (semeRicerca.endsWith(QueryBuilderSqlServer.RICERCA_JOLLY_CHAR)) {
        /* CASO ciao* */
        semeRicerca = semeRicerca.replace(QueryBuilderSqlServer.RICERCA_JOLLY_CHAR, "");
        res.append(campo + " LIKE '" + encodeStringSQL(semeRicerca) + "%'");
    } else if (semeRicerca.startsWith(QueryBuilderSqlServer.RICERCA_JOLLY_CHAR)) {
        /* CASO *ciao */
        semeRicerca = semeRicerca.replace(QueryBuilderSqlServer.RICERCA_JOLLY_CHAR, "");
        res.append(campo + " LIKE '%" + encodeStringSQL(semeRicerca) + "'");
    } else {
        /* CASO ciao */
        res.append(campo + " = '" + encodeStringSQL(semeRicerca) + "'");
    }

    return res.toString();
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.EventNode.java

/**
 * Fires a specified event on this element (IE only). See the
 * <a href="http://msdn.microsoft.com/en-us/library/ms536423.aspx">MSDN documentation</a>
 * for more information.//from  w  w  w.j  a  v a  2s.  co m
 * @param type specifies the name of the event to fire.
 * @param event specifies the event object from which to obtain event object properties.
 * @return <tt>true</tt> if the event fired successfully, <tt>false</tt> if it was canceled
 */
@JsxFunction(@WebBrowser(IE))
public boolean fireEvent(final String type, Event event) {
    if (event == null) {
        event = new MouseEvent();
    }

    // Create the event, whose class will depend on the type specified.
    final String cleanedType = StringUtils.removeStart(type.toLowerCase(), "on");
    if (MouseEvent.isMouseEvent(cleanedType)) {
        event.setPrototype(getPrototype(MouseEvent.class));
    } else {
        event.setPrototype(getPrototype(Event.class));
    }
    event.setParentScope(getWindow());

    // These four properties have predefined values, independent of the template.
    event.setCancelBubble(false);
    event.setReturnValue(Boolean.TRUE);
    event.setSrcElement(this);
    event.setEventType(cleanedType);

    fireEvent(event);
    return ((Boolean) event.getReturnValue()).booleanValue();
}