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.eclipse.leshan.standalone.servlet.ClientServlet.java

/**
 * {@inheritDoc}/*from   w ww  .java 2s  .c o  m*/
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] path = StringUtils.split(req.getPathInfo(), '/');
    String clientEndpoint = path[0];

    // /clients/endPoint/LWRequest/observe : do LightWeight M2M observe request on a given client.
    if (path.length >= 4 && "observe".equals(path[path.length - 1])) {
        try {
            String target = StringUtils.substringBetween(req.getPathInfo(), clientEndpoint, "/observe");
            Client client = server.getClientRegistry().get(clientEndpoint);
            if (client != null) {
                ObserveRequest request = new ObserveRequest(target);
                LwM2mResponse cResponse = server.send(client, request, TIMEOUT);
                processDeviceResponse(req, resp, cResponse);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (IllegalArgumentException e) {
            LOG.warn("Invalid request", e);
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().append(e.getMessage()).flush();
        } catch (ResourceAccessException | RequestFailedException e) {
            LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()),
                    e);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().append(e.getMessage()).flush();
        }
        return;
    }

    String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);

    // /clients/endPoint/LWRequest : do LightWeight M2M execute request on a given client.
    if (path.length == 4) {
        try {
            Client client = server.getClientRegistry().get(clientEndpoint);
            if (client != null) {
                ExecuteRequest request = new ExecuteRequest(target, IOUtils.toByteArray(req.getInputStream()),
                        null);
                LwM2mResponse cResponse = server.send(client, request, TIMEOUT);
                processDeviceResponse(req, resp, cResponse);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (IllegalArgumentException e) {
            LOG.warn("Invalid request", e);
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().append(e.getMessage()).flush();
        } catch (ResourceAccessException | RequestFailedException e) {
            LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()),
                    e);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().append(e.getMessage()).flush();
        }
        return;
    }

    // /clients/endPoint/LWRequest : do LightWeight M2M create request on a given client.
    if (2 <= path.length && path.length <= 3) {
        try {
            Client client = server.getClientRegistry().get(clientEndpoint);
            if (client != null) {
                LwM2mResponse cResponse = this.createRequest(client, target, req, resp);
                processDeviceResponse(req, resp, cResponse);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (IllegalArgumentException e) {
            LOG.warn("Invalid request", e);
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().append(e.getMessage()).flush();
        } catch (ResourceAccessException | RequestFailedException e) {
            LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()),
                    e);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().append(e.getMessage()).flush();
        }
        return;
    }
}

From source file:org.eclipse.leshan.standalone.servlet.ClientServlet.java

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] path = StringUtils.split(req.getPathInfo(), '/');
    String clientEndpoint = path[0];

    // /clients/endPoint/LWRequest/observe : cancel observation for the given resource.
    if (path.length >= 4 && "observe".equals(path[path.length - 1])) {
        try {//from   w  w w  .j a  v  a 2s  .co m
            String target = StringUtils.substringsBetween(req.getPathInfo(), clientEndpoint, "/observe")[0];
            Client client = server.getClientRegistry().get(clientEndpoint);
            if (client != null) {
                server.getObservationRegistry().cancelObservation(client, target);
                resp.setStatus(HttpServletResponse.SC_OK);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (IllegalArgumentException e) {
            LOG.warn("Invalid request", e);
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().append(e.getMessage()).flush();
        } catch (ResourceAccessException | RequestFailedException e) {
            LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()),
                    e);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().append(e.getMessage()).flush();
        }
        return;
    }

    // /clients/endPoint/LWRequest/ : delete instance
    try {
        String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
        Client client = server.getClientRegistry().get(clientEndpoint);
        if (client != null) {
            DeleteRequest request = new DeleteRequest(target);
            LwM2mResponse cResponse = server.send(client, request, TIMEOUT);
            processDeviceResponse(req, resp, cResponse);
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
        }
    } catch (IllegalArgumentException e) {
        LOG.warn("Invalid request", e);
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().append(e.getMessage()).flush();
    } catch (ResourceAccessException | RequestFailedException e) {
        LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.getWriter().append(e.getMessage()).flush();
    }
}

From source file:org.eclipse.skalli.core.rest.JSONRestReader.java

@Override
public String key() throws IOException {
    assertNotFinal();//from   www.j a v a2 s  . c om
    if (lookAhead == null && sequenceState != EXPECT_KEY) {
        throw new IllegalStateException("Key expected");
    }
    String key = lookAhead;
    if (key != null) {
        lookAhead = null;
        return key;
    }
    key = json.nextName();
    sequenceState = EXPECT_VALUE;
    return isSet(PREFIXED_ATTRIBUTES) ? StringUtils.removeStart(key, "@") : key; //$NON-NLS-1$
}

From source file:org.eclipse.skalli.gerrit.client.internal.GerritClientImpl.java

/**
 * Utility method for checking accounts.
 *
 * This indirection was introduced to allow splitting the call if the parameter list is huge.
 * Depending on the database this could easily fail. Hence split it into separate SQL queries
 * and merge the results./*from  w w  w.j av  a  2s .c om*/
 *
 * @throws ConnectionException in case of connection / communication problems
 * @throws CommandException    in case of unsuccessful commands
 */
private Collection<String> queryKnownAccounts(Collection<String> variousAccounts)
        throws ConnectionException, CommandException {
    final List<String> result = new ArrayList<String>();

    final StringBuffer sb = new StringBuffer();
    sb.append("SELECT external_id FROM ").append(GSQL.Tables.ACCOUNT_EXTERNAL_IDS)
            .append(" WHERE external_id IN (");

    boolean noRealParameters = true;
    for (String variousAccount : variousAccounts) {
        if (!StringUtils.isBlank(variousAccount)) {
            sb.append("'").append(ACCOUNTS_PREFIX).append(variousAccount).append("', ");
            noRealParameters = false;
        }
    }
    sb.delete(sb.length() - 2, sb.length());
    sb.append(");");

    if (noRealParameters) {
        return result;
    }
    final List<String> gsqlResult = gsql(sb.toString(), ResultFormat.JSON);
    for (final String entry : gsqlResult) {
        if (isRow(entry)) {
            result.add(
                    StringUtils.removeStart(JSONUtil.getString(entry, "columns.external_id"), ACCOUNTS_PREFIX));
        }
    }

    return result;

}

From source file:org.eclipse.smarthome.binding.homematic.handler.HomematicThingHandler.java

@Override
public void handleConfigurationUpdate(Map<String, Object> configurationParameters)
        throws ConfigValidationException {
    super.handleConfigurationUpdate(configurationParameters);

    try {//from  w w  w  .  ja  v a  2s.c  o  m
        HomematicGateway gateway = getHomematicGateway();
        HmDevice device = gateway.getDevice(UidUtils.getHomematicAddress(getThing()));

        for (Entry<String, Object> configurationParameter : configurationParameters.entrySet()) {
            String key = configurationParameter.getKey();
            Object newValue = configurationParameter.getValue();

            if (key.startsWith("HMP_")) {
                key = StringUtils.removeStart(key, "HMP_");
                Integer channelNumber = NumberUtils.toInt(StringUtils.substringBefore(key, "_"));
                String dpName = StringUtils.substringAfter(key, "_");

                HmDatapointInfo dpInfo = new HmDatapointInfo(device.getAddress(), HmParamsetType.MASTER,
                        channelNumber, dpName);
                HmDatapoint dp = device.getChannel(channelNumber).getDatapoint(dpInfo);

                if (dp != null) {
                    try {
                        if (newValue != null) {
                            if (newValue instanceof BigDecimal) {
                                final BigDecimal decimal = (BigDecimal) newValue;
                                if (dp.isIntegerType()) {
                                    newValue = decimal.intValue();
                                } else if (dp.isFloatType()) {
                                    newValue = decimal.doubleValue();
                                }
                            }
                            if (ObjectUtils.notEqual(dp.isEnumType() ? dp.getOptionValue() : dp.getValue(),
                                    newValue)) {
                                sendDatapoint(dp, new HmDatapointConfig(), newValue);
                            }
                        }
                    } catch (IOException ex) {
                        logger.error("Error setting thing property {}: {}", dpInfo, ex.getMessage());
                    }
                } else {
                    logger.error("Can't find datapoint for thing property {}", dpInfo);
                }
            }
        }
        gateway.triggerDeviceValuesReload(device);
    } catch (HomematicClientException | GatewayNotAvailableException ex) {
        logger.error("Error setting thing properties: {}", ex.getMessage(), ex);
    }
}

From source file:org.eclipse.wb.android.internal.model.property.event.ListenerInfo.java

/**
 * @return the name of listener method, to display for user. For example <code>key</code> for
 *         <code>addKeyListener()</code>.
 *///from w ww  .  ja  v a  2 s . c o m
private static String _getListenerSimpleName(Method addListenerMethod) {
    String name = addListenerMethod.getName();
    // convert into simple name
    name = StringUtils.removeStart(name, "set");
    name = StringUtils.removeEnd(name, "Listener");
    name = StringUtils.uncapitalize(name);
    // if become empty, use full name
    if (name.length() == 0) {
        name = addListenerMethod.getName();
    }
    return name;
}

From source file:org.eclipse.wb.android.internal.support.AndroidBridge.java

/**
 * Returns whether the given <var>style</var> is a theme. This is done by making sure the parent
 * is a theme./*  w  w  w.j  av a 2 s.  c om*/
 * 
 * See {@link
 * com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationComposite#
 * isTheme(ResourceValue, Map<String, ResourceValue>)}
 * 
 * @param value
 *          the style to check
 * @param styleMap
 *          the map of styles for the current project. Key is the style name.
 * @return True if the given <var>style</var> is a theme.
 */
private boolean isTheme(ResourceValue value, Map<String, ResourceValue> styleMap) {
    String ANDROID_NS_NAME_PREFIX = "android:";
    String name = value.getName();
    if (value instanceof StyleResourceValue) {
        StyleResourceValue style = (StyleResourceValue) value;
        boolean frameworkStyle = false;
        String parentStyle = style.getParentStyle();
        if (parentStyle == null) {
            // if there is no specified parent style we look an implied one.
            // For instance 'Theme.light' is implied child style of 'Theme',
            // and 'Theme.light.fullscreen' is implied child style of 'Theme.light'
            int index = name.lastIndexOf('.');
            if (index != -1) {
                parentStyle = name.substring(0, index);
            }
        } else {
            // remove the useless @ if it's there
            parentStyle = StringUtils.removeStart(parentStyle, "@");
            // check for framework identifier.
            if (parentStyle.startsWith(ANDROID_NS_NAME_PREFIX)) {
                frameworkStyle = true;
                parentStyle = parentStyle.substring(ANDROID_NS_NAME_PREFIX.length());
            }
            // at this point we could have the format style/<name>. we want only the name
            if (parentStyle.startsWith("style/")) {
                parentStyle = parentStyle.substring("style/".length());
            }
        }
        if (parentStyle != null && !frameworkStyle) {
            // if it's a project style, we check this is a theme.
            value = styleMap.get(parentStyle);
            if (value != null) {
                return isTheme(value, styleMap);
            }
        }
    }
    return name.startsWith("Theme.") || name.equals("Theme");
}

From source file:org.eclipse.wb.android.internal.support.IdSupport.java

/**
 * Removes "@id/" or "@id+/" prefixes resulting id suitable to find the View with.
 *///ww w.  ja  va 2s.  c  o  m
public static String getSimpleId(String id) {
    id = StringUtils.removeStart(id, NEW_ID_PREFIX);
    id = StringUtils.removeStart(id, ID_PREFIX);
    return id;
}

From source file:org.eclipse.wb.internal.core.editor.errors.report2.ProjectReportEntry.java

public void write(final ZipOutputStream zipStream) throws Exception {
    // prepare project
    m_project.refreshLocal(IResource.DEPTH_INFINITE, null);
    // traverse project files
    m_project.accept(new IResourceVisitor() {
        public boolean visit(IResource resource) throws CoreException {
            try {
                // skip non-local, unresolved files and files with size more than MAX_FILE_SIZE 
                long fileSize = getResourceSize(resource);
                if (fileSize == 0 || fileSize > MAX_FILE_SIZE) {
                    return true;
                }/*  w w w. j a  va2s .com*/
                // skip binaries
                String fileExtension = resource.getFileExtension();
                if (fileExtension == null || fileExtension.equalsIgnoreCase("class")) {
                    return false;
                }
                // open stream and put it contents to zip
                IFile file = (IFile) resource;
                InputStream fileStream = file.getContents();
                // remove leading slash
                String filePath = "project/"
                        + StringUtils.removeStart(file.getFullPath().toPortableString(), File.separator);
                zipStream.putNextEntry(new ZipEntry(filePath));
                try {
                    IOUtils.copy(fileStream, zipStream);
                } finally {
                    zipStream.closeEntry();
                    IOUtils.closeQuietly(fileStream);
                }
            } catch (Throwable e) {
                DesignerPlugin.log(e);
            }
            return true;
        }
    });
}

From source file:org.eclipse.wb.internal.core.model.generic.FlowContainerFactory.java

private static AssociationObjectFactory getAssociation_invocationChild(String associationString) {
    associationString = StringUtils.removeStart(associationString, "invocationChild ");
    Assert.isTrue(associationString.startsWith("%parent%."),
            "Association 'invocationChild' should start with %%parent%%., but '%s' found.", associationString);
    return AssociationObjectFactories.invocationChild(associationString, false);
}