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.gyrex.jobs.internal.schedules.ScheduleManagerImpl.java

private String toExternalId(final String internalId) {
    return StringUtils.removeStart(internalId, internalIdPrefix);
}

From source file:org.eclipse.gyrex.jobs.internal.util.ContextHashUtil.java

public String toExternalId(final String internalId) {
    return StringUtils.removeStart(internalId, internalIdPrefix);
}

From source file:org.eclipse.gyrex.monitoring.internal.mbeans.MetricSetMBean.java

private void initialize() {
    final List<OpenMBeanAttributeInfoSupport> attributes = new ArrayList<OpenMBeanAttributeInfoSupport>();
    final OpenMBeanConstructorInfoSupport[] constructors = new OpenMBeanConstructorInfoSupport[0];
    final List<OpenMBeanOperationInfoSupport> operations = new ArrayList<OpenMBeanOperationInfoSupport>(1);
    final MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[0];

    // common attribute
    attributes/*from w w w .ja  va 2  s . co  m*/
            .add(new OpenMBeanAttributeInfoSupport(ID, "MetricSet Id", SimpleType.STRING, true, false, false));
    attributes.add(new OpenMBeanAttributeInfoSupport(DESCRIPTION, "MetricSet Description", SimpleType.STRING,
            true, false, false));

    // service property attributes
    try {
        final String[] propertyTypeNames = new String[] { "key", "value" };
        propertyType = new CompositeType("property", "A property with name and value.", propertyTypeNames,
                new String[] { "Name", "Value" }, new OpenType[] { SimpleType.STRING, SimpleType.STRING });
        propertyTableType = new TabularType(PROPERTIES, "A lst of properties.", propertyType,
                new String[] { "key" });
        attributes.add(new OpenMBeanAttributeInfoSupport(PROPERTIES, "MetricSet Properties", propertyTableType,
                true, false, false));

        // pre-build service properties
        properties = new TabularDataSupport(propertyTableType);
        final String[] propertyKeys = reference.getPropertyKeys();
        for (final String serviceProperty : propertyKeys) {
            if (serviceProperty.startsWith("gyrex.") || serviceProperty.equals(Constants.SERVICE_DESCRIPTION)
                    || serviceProperty.equals(Constants.SERVICE_VENDOR)) {
                final Object value = reference.getProperty(serviceProperty);
                if (value == null) {
                    continue;
                }
                if (isConvertibleToString(value.getClass())) {
                    final Object[] values = { serviceProperty, String.valueOf(value) };
                    properties.put(new CompositeDataSupport(propertyType, propertyTypeNames, values));
                }
            }
        }
    } catch (final OpenDataException e) {
        attributes.add(new OpenMBeanAttributeInfoSupport("propertiesError",
                "Exception occured while determining properties. " + e.toString(), SimpleType.STRING, true,
                false, false));
    }

    // metrics
    final List<BaseMetric> metrics = metricSet.getMetrics();
    metricTypesByAttributeName = new HashMap<String, CompositeType>(metrics.size());
    metricByAttributeName = new HashMap<String, BaseMetric>(metrics.size());
    for (final BaseMetric metric : metrics) {
        final String attributeName = StringUtils.removeStart(metric.getId(), metricSet.getId() + ".");
        try {
            final CompositeType type = getType(metric);
            if (type != null) {
                metricTypesByAttributeName.put(attributeName, type);
                metricByAttributeName.put(attributeName, metric);
                attributes.add(new OpenMBeanAttributeInfoSupport(attributeName, metric.getId(), type, true,
                        false, false));
            }
        } catch (final OpenDataException e) {
            attributes.add(new OpenMBeanAttributeInfoSupport(attributeName + "Error",
                    "Exception occured while determining properties. " + e.toString(), SimpleType.STRING, true,
                    false, false));
        }
    }

    // reset operation for metric
    operations.add(new OpenMBeanOperationInfoSupport(RESET_STATS, "reset the metric statistics", null,
            SimpleType.VOID, MBeanOperationInfo.ACTION));

    // build the info
    beanInfo = new OpenMBeanInfoSupport(this.getClass().getName(), metricSet.getDescription(),
            attributes.toArray(new OpenMBeanAttributeInfoSupport[attributes.size()]), constructors,
            operations.toArray(new OpenMBeanOperationInfoSupport[operations.size()]), notifications);
}

From source file:org.eclipse.gyrex.monitoring.internal.MetricSetTracker.java

private ObjectName getObjectName(final ServiceReference<MetricSet> reference, final MetricSet metricSet)
        throws MalformedObjectNameException {
    // get symbolic name
    final String symbolicName = reference.getBundle().getSymbolicName();

    // set properties
    final String[] propertyKeys = reference.getPropertyKeys();
    final Hashtable<String, String> properties = new Hashtable<String, String>(propertyKeys.length + 2);

    // common properties first
    properties.put("type", "MetricSet");
    properties.put("name", StringUtils.removeStart(metricSet.getId(), symbolicName + "."));

    // we also remember the service id in order to allow multiple metrics instances with same id
    properties.put("service.id", String.valueOf(reference.getProperty(Constants.SERVICE_ID)));

    // check additional metric set properties
    for (final Entry<String, String> property : metricSet.getProperties().entrySet()) {
        // prefix each with "metric." to avoid name clash with common properties
        properties.put("metric.".concat(property.getKey()), property.getValue());
    }/*from  w  w w  .  j  a va  2s.c  om*/

    // create object name
    return new ObjectName(symbolicName, properties);
}

From source file:org.eclipse.leshan.server.demo.servlet.ClientServlet.java

/**
 * {@inheritDoc}//from w w w  .j  ava  2 s . com
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // all registered clients
    if (req.getPathInfo() == null) {
        Collection<Registration> registrations = new ArrayList<>();
        for (Iterator<Registration> iterator = server.getRegistrationService().getAllRegistrations(); iterator
                .hasNext();) {
            registrations.add(iterator.next());
        }

        String json = this.gson.toJson(registrations.toArray(new Registration[] {}));
        resp.setContentType("application/json");
        resp.getOutputStream().write(json.getBytes("UTF-8"));
        resp.setStatus(HttpServletResponse.SC_OK);
        return;
    }

    String[] path = StringUtils.split(req.getPathInfo(), '/');
    if (path.length < 1) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid path");
        return;
    }
    String clientEndpoint = path[0];

    // /endPoint : get client
    if (path.length == 1) {
        Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
        if (registration != null) {
            resp.setContentType("application/json");
            resp.getOutputStream().write(this.gson.toJson(registration).getBytes("UTF-8"));
            resp.setStatus(HttpServletResponse.SC_OK);
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
        }
        return;
    }

    // /clients/endPoint/LWRequest : do LightWeight M2M read request on a given client.
    try {
        String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
        Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
        if (registration != null) {
            // get content format
            String contentFormatParam = req.getParameter(FORMAT_PARAM);
            ContentFormat contentFormat = contentFormatParam != null
                    ? ContentFormat.fromName(contentFormatParam.toUpperCase())
                    : null;

            // create & process request
            ReadRequest request = new ReadRequest(contentFormat, target);
            ReadResponse cResponse = server.send(registration, 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 (RuntimeException | InterruptedException e) {
        handleException(e, resp);
    }
}

From source file:org.eclipse.leshan.server.demo.servlet.ClientServlet.java

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

    // at least /endpoint/objectId/instanceId
    if (path.length < 3) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid path");
        return;
    }

    try {
        String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
        Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
        if (registration != null) {
            // get content format
            String contentFormatParam = req.getParameter(FORMAT_PARAM);
            ContentFormat contentFormat = contentFormatParam != null
                    ? ContentFormat.fromName(contentFormatParam.toUpperCase())
                    : null;

            // create & process request
            LwM2mNode node = extractLwM2mNode(target, req);
            WriteRequest request = new WriteRequest(Mode.REPLACE, contentFormat, target, node);
            WriteResponse cResponse = server.send(registration, 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 (RuntimeException | InterruptedException e) {
        handleException(e, resp);
    }
}

From source file:org.eclipse.leshan.server.demo.servlet.ClientServlet.java

/**
 * {@inheritDoc}//from   w  ww .ja  va 2s  . c om
 */
@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");
            Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
            if (registration != null) {
                // get content format
                String contentFormatParam = req.getParameter(FORMAT_PARAM);
                ContentFormat contentFormat = contentFormatParam != null
                        ? ContentFormat.fromName(contentFormatParam.toUpperCase())
                        : null;

                // create & process request
                ObserveRequest request = new ObserveRequest(contentFormat, target);
                ObserveResponse cResponse = server.send(registration, 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 (RuntimeException | InterruptedException e) {
            handleException(e, resp);
        }
        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 {
            Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
            if (registration != null) {
                ExecuteRequest request = new ExecuteRequest(target, IOUtils.toString(req.getInputStream()));
                ExecuteResponse cResponse = server.send(registration, 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 (RuntimeException | InterruptedException e) {
            handleException(e, resp);
        }
        return;
    }

    // /clients/endPoint/LWRequest : do LightWeight M2M create request on a given client.
    if (2 <= path.length && path.length <= 3) {
        try {
            Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
            if (registration != null) {
                // get content format
                String contentFormatParam = req.getParameter(FORMAT_PARAM);
                ContentFormat contentFormat = contentFormatParam != null
                        ? ContentFormat.fromName(contentFormatParam.toUpperCase())
                        : null;

                // create & process request
                LwM2mNode node = extractLwM2mNode(target, req);
                if (node instanceof LwM2mObjectInstance) {
                    CreateRequest request = new CreateRequest(contentFormat, target,
                            (LwM2mObjectInstance) node);
                    CreateResponse cResponse = server.send(registration, request, TIMEOUT);
                    processDeviceResponse(req, resp, cResponse);
                } else {
                    throw new IllegalArgumentException("payload must contain an object instance");
                }
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (RuntimeException | InterruptedException e) {
            handleException(e, resp);
        }
        return;
    }
}

From source file:org.eclipse.leshan.server.demo.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 {/*  w  ww  .  j a va2s  . co m*/
            String target = StringUtils.substringsBetween(req.getPathInfo(), clientEndpoint, "/observe")[0];
            Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
            if (registration != null) {
                server.getObservationService().cancelObservations(registration, 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 (RuntimeException e) {
            handleException(e, resp);
        }
        return;
    }

    // /clients/endPoint/LWRequest/ : delete instance
    try {
        String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
        Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
        if (registration != null) {
            DeleteRequest request = new DeleteRequest(target);
            DeleteResponse cResponse = server.send(registration, 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 (RuntimeException | InterruptedException e) {
        handleException(e, resp);
    }
}

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

/**
 * {@inheritDoc}/*from   w  ww  .  j  a v  a 2  s .  c  o  m*/
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // all registered clients
    if (req.getPathInfo() == null) {
        Collection<Client> clients = server.getClientRegistry().allClients();

        String json = this.gson.toJson(clients.toArray(new Client[] {}));
        resp.setContentType("application/json");
        resp.getOutputStream().write(json.getBytes("UTF-8"));
        resp.setStatus(HttpServletResponse.SC_OK);
        return;
    }

    String[] path = StringUtils.split(req.getPathInfo(), '/');
    if (path.length < 1) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid path");
        return;
    }
    String clientEndpoint = path[0];

    // /endPoint : get client
    if (path.length == 1) {
        Client client = server.getClientRegistry().get(clientEndpoint);
        if (client != null) {
            resp.setContentType("application/json");
            resp.getOutputStream().write(this.gson.toJson(client).getBytes("UTF-8"));
            resp.setStatus(HttpServletResponse.SC_OK);
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
        }
        return;
    }

    // /clients/endPoint/LWRequest : do LightWeight M2M read request on a given client.
    try {
        String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
        Client client = server.getClientRegistry().get(clientEndpoint);
        if (client != null) {
            ReadRequest request = new ReadRequest(target);
            ValueResponse 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.leshan.standalone.servlet.ClientServlet.java

/**
 * {@inheritDoc}/*from  www .ja  v a2  s.c  om*/
 */
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] path = StringUtils.split(req.getPathInfo(), '/');
    String clientEndpoint = path[0];

    // at least /endpoint/objectId/instanceId
    if (path.length < 3) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid path");
        return;
    }

    try {
        String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
        Client client = server.getClientRegistry().get(clientEndpoint);
        if (client != null) {
            LwM2mResponse cResponse = this.writeRequest(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();
    }
}