Example usage for org.apache.commons.lang3 StringUtils substringAfter

List of usage examples for org.apache.commons.lang3 StringUtils substringAfter

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils substringAfter.

Prototype

public static String substringAfter(final String str, final String separator) 

Source Link

Document

Gets the substring after the first occurrence of a separator.

Usage

From source file:net.sf.dynamicreports.test.jasper.chart.ChartSeriesColorsByNameTest.java

@Override
public void test() {
    super.test();

    numberOfPagesTest(1);//from  w w w  . ja v a 2 s . co  m

    chartCountTest("summary.chart1", 1);
    JFreeChart chart = getChart("summary.chart1", 0);
    CategoryItemRenderer renderer1 = chart.getCategoryPlot().getRenderer();
    CategoryDataset dataset1 = chart.getCategoryPlot().getDataset();
    for (int i = 0; i < dataset1.getRowCount(); i++) {
        String key = (String) dataset1.getRowKey(i);
        Assert.assertNotNull("null series color", colors.get(key));
        Assert.assertEquals("series color", colors.get(key), renderer1.getSeriesPaint(i));
    }

    chartCountTest("summary.chart2", 1);
    chart = getChart("summary.chart2", 0);
    CategoryItemRenderer renderer2 = chart.getCategoryPlot().getRenderer();
    CategoryDataset dataset2 = chart.getCategoryPlot().getDataset();
    for (int i = 0; i < dataset2.getRowCount(); i++) {
        String key = (String) dataset2.getRowKey(i);
        key = StringUtils.substringAfter(key, GroupedStackedBarRendererCustomizer.GROUP_SERIES_KEY);
        Assert.assertNotNull("null series color", colors.get(key));
        Assert.assertEquals("series color", colors.get(key), renderer2.getSeriesPaint(i));
    }
    for (int i = 0; i < chart.getCategoryPlot().getFixedLegendItems().getItemCount(); i++) {
        LegendItem legendItem = chart.getCategoryPlot().getFixedLegendItems().get(i);
        Assert.assertNotNull("null series color", colors.get(legendItem.getLabel()));
        Assert.assertEquals("series color", colors.get(legendItem.getLabel()), legendItem.getFillPaint());
    }

    chartCountTest("summary.chart3", 1);
    chart = getChart("summary.chart3", 0);
    PiePlot plot3 = (PiePlot) chart.getPlot();
    PieDataset dataset3 = plot3.getDataset();
    for (int i = 0; i < dataset3.getItemCount(); i++) {
        String key = (String) dataset3.getKey(i);
        Assert.assertNotNull("null series color", colors.get(key));
        Assert.assertEquals("series color", colors.get(key), plot3.getSectionPaint(key));
    }

    chartCountTest("summary.chart4", 1);
    chart = getChart("summary.chart4", 0);
    XYItemRenderer renderer4 = chart.getXYPlot().getRenderer();
    XYDataset dataset4 = chart.getXYPlot().getDataset();
    for (int i = 0; i < dataset4.getSeriesCount(); i++) {
        String key = (String) dataset4.getSeriesKey(i);
        Assert.assertNotNull("null series color", colors.get(key));
        Assert.assertEquals("series color", colors.get(key), renderer4.getSeriesPaint(i));
    }
}

From source file:com.evolveum.midpoint.notifications.impl.api.transports.SimpleSmsTransport.java

@Override
public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) {

    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addArbitraryObjectCollectionAsParam("message recipient(s)", message.getTo());
    result.addParam("message subject", message.getSubject());

    SystemConfigurationType systemConfiguration = NotificationFunctionsImpl
            .getSystemConfiguration(cacheRepositoryService, result);
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null) {
        String msg = "No notifications are configured. SMS notification to " + message.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);/*from   ww w .  ja  v a2 s.c o  m*/
        result.recordWarning(msg);
        return;
    }

    String smsConfigName = StringUtils.substringAfter(transportName, NAME + ":");
    SmsConfigurationType found = null;
    for (SmsConfigurationType smsConfigurationType : systemConfiguration.getNotificationConfiguration()
            .getSms()) {
        if (StringUtils.isEmpty(smsConfigName) && smsConfigurationType.getName() == null
                || StringUtils.isNotEmpty(smsConfigName)
                        && smsConfigName.equals(smsConfigurationType.getName())) {
            found = smsConfigurationType;
            break;
        }
    }

    if (found == null) {
        String msg = "SMS configuration '" + smsConfigName + "' not found. SMS notification to "
                + message.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    SmsConfigurationType smsConfigurationType = found;
    String logToFile = smsConfigurationType.getLogToFile();
    if (logToFile != null) {
        TransportUtil.logToFile(logToFile, TransportUtil.formatToFileNew(message, transportName), LOGGER);
    }
    String file = smsConfigurationType.getRedirectToFile();
    if (file != null) {
        writeToFile(message, file, null, emptyList(), null, result);
        return;
    }

    if (smsConfigurationType.getGateway().isEmpty()) {
        String msg = "SMS gateway(s) are not defined, notification to " + message.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    String from;
    if (message.getFrom() != null) {
        from = message.getFrom();
    } else if (smsConfigurationType.getDefaultFrom() != null) {
        from = smsConfigurationType.getDefaultFrom();
    } else {
        from = "";
    }

    if (message.getTo().isEmpty()) {
        String msg = "There is no recipient to send the notification to.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    List<String> to = message.getTo();
    assert to.size() > 0;

    for (SmsGatewayConfigurationType smsGatewayConfigurationType : smsConfigurationType.getGateway()) {
        OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway");
        resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName());
        try {
            ExpressionVariables variables = getDefaultVariables(from, to, message);
            HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET);
            ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(),
                    smsGatewayConfigurationType.getUrl());
            String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task,
                    result);
            LOGGER.debug("Sending SMS to URL {} (method {})", url, method);
            if (url == null) {
                throw new IllegalArgumentException("No URL specified");
            }

            List<String> headersList = evaluateExpressionsChecked(
                    smsGatewayConfigurationType.getHeadersExpression(), variables,
                    "sms gateway request headers", task, result);
            LOGGER.debug("Using request headers:\n{}", headersList);

            String encoding = defaultIfNull(smsGatewayConfigurationType.getBodyEncoding(),
                    StandardCharsets.ISO_8859_1.name());
            String body = evaluateExpressionChecked(smsGatewayConfigurationType.getBodyExpression(), variables,
                    "sms gateway request body", task, result);
            LOGGER.debug("Using request body text (encoding: {}):\n{}", encoding, body);

            if (smsGatewayConfigurationType.getLogToFile() != null) {
                TransportUtil.logToFile(smsGatewayConfigurationType.getLogToFile(),
                        formatToFile(message, url, headersList, body), LOGGER);
            }
            if (smsGatewayConfigurationType.getRedirectToFile() != null) {
                writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, headersList, body,
                        resultForGateway);
                result.computeStatus();
                return;
            } else {
                HttpClientBuilder builder = HttpClientBuilder.create();
                String username = smsGatewayConfigurationType.getUsername();
                ProtectedStringType password = smsGatewayConfigurationType.getPassword();
                if (username != null) {
                    CredentialsProvider provider = new BasicCredentialsProvider();
                    String plainPassword = password != null ? protector.decryptString(password) : null;
                    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username,
                            plainPassword);
                    provider.setCredentials(AuthScope.ANY, credentials);
                    builder = builder.setDefaultCredentialsProvider(provider);
                }
                HttpClient client = builder.build();
                HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
                        client);
                ClientHttpRequest request = requestFactory.createRequest(new URI(url),
                        HttpUtil.toHttpMethod(method));
                setHeaders(request, headersList);
                if (body != null) {
                    request.getBody().write(body.getBytes(encoding));
                }
                ClientHttpResponse response = request.execute();
                LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText());
                if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) {
                    throw new SystemException("SMS gateway communication failed: " + response.getStatusCode()
                            + ": " + response.getStatusText());
                }
                LOGGER.info("Message sent successfully to {} via gateway {}.", message.getTo(),
                        smsGatewayConfigurationType.getName());
                resultForGateway.recordSuccess();
                result.recordSuccess();
                return;
            }
        } catch (Throwable t) {
            String msg = "Couldn't send SMS to " + message.getTo() + " via "
                    + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any";
            LoggingUtils.logException(LOGGER, msg, t);
            resultForGateway.recordFatalError(msg, t);
        }
    }
    LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent.");
    result.recordWarning("Notification to " + message.getTo() + " could not be sent.");
}

From source file:com.zc.orm.hibernate.HibernateDao.java

private String prepareCountHql(String orgHql) {
    String fromHql = orgHql;/*w w w  .  j ava 2s.c o m*/
    // select??order by???count,??
    fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
    fromHql = StringUtils.substringBefore(fromHql, "order by");
    String countHql = "select count(*) " + fromHql;
    return countHql;
}

From source file:com.neatresults.mgnltweaks.neatu2b.ui.form.field.U2BField.java

/**
 * Initialize the field. <br>/*from  w  ww . j  av  a2 s .c  o  m*/
 * Create as many configured Field as we have related values already stored.
 */
@Override
protected void initFields(final PropertysetItem newValue) {
    root.removeAllComponents();
    final TextField id = createTextField("Id", newValue);
    root.addComponent(id);
    final TextField title = createTextField("Title", newValue);
    root.addComponent(title);

    final TextFieldDefinition def = new TextFieldBuilder("description").label("Description").rows(3)
            .definition();
    final TextArea description = (TextArea) createLocalField(def, newValue.getItemProperty(def.getName()),
            false);
    newValue.addItemProperty(def.getName(), description.getPropertyDataSource());
    description.setNullRepresentation("");
    description.setWidth("100%");
    description.setNullSettingAllowed(true);
    root.addComponent(description);

    HorizontalLayout ddLine = new HorizontalLayout();
    final TextField publishedAt = createTextField("Published", newValue);
    ddLine.addComponent(publishedAt);
    final TextField duration = createTextField("Duration", newValue);
    ddLine.addComponent(duration);
    ddLine.addComponent(createTextField("Definition", newValue));

    Button fetchButton = new Button("Fetch metadata");
    fetchButton.addStyleName("magnoliabutton");
    fetchButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {

            String idStr = id.getValue();
            // extract id from url when whole url is passed
            if (idStr.startsWith("http")) {
                idStr = StringUtils.substringBefore(StringUtils.substringAfter(idStr, "?v="), "&");
            }

            U2BService service = null;
            try {
                RestEasyClient client = (RestEasyClient) restClientRegistry.getRestClient("youtube");
                service = client.getClientService(U2BService.class);
            } catch (RegistrationException e) {
                log.error("Failed to get a client for [" + U2BService.class.getName() + "] with: "
                        + e.getMessage(), e);
            }
            if (service != null) {
                String key = u2bModule.getGoogleKey();
                JsonNode response = service.meta(idStr, "snippet", key);
                try {
                    if (response.get("items").getElements().hasNext()) {
                        JsonNode videoItem = response.get("items").getElements().next();
                        String descriptionStr = videoItem.get("snippet").get("description").getTextValue();
                        newValue.getItemProperty("description").setValue(descriptionStr);
                        String titleStr = videoItem.get("snippet").get("title").getTextValue();
                        newValue.getItemProperty("title").setValue(titleStr);
                        Iterator<Entry<String, JsonNode>> thumbs = videoItem.get("snippet").get("thumbnails")
                                .getFields();
                        while (thumbs.hasNext()) {
                            Entry<String, JsonNode> entry = thumbs.next();
                            newValue.getItemProperty(entry.getKey() + "Url")
                                    .setValue(entry.getValue().get("url").getTextValue());
                            newValue.getItemProperty(entry.getKey() + "Width")
                                    .setValue("" + entry.getValue().get("width").getLongValue());
                            newValue.getItemProperty(entry.getKey() + "Height")
                                    .setValue("" + entry.getValue().get("height").getLongValue());
                        }
                        String publishedAtStr = videoItem.get("snippet").get("publishedAt").getTextValue();
                        newValue.getItemProperty("published").setValue(publishedAtStr);
                    }
                } catch (Exception e) {
                    log.error("Failed to parse the video metadata.", e);
                }

                response = service.meta(idStr, "contentDetails", key);
                try {
                    if (response.get("items").getElements().hasNext()) {
                        JsonNode videoItem = response.get("items").getElements().next();
                        String durationStr = videoItem.get("contentDetails").get("duration").getTextValue();
                        newValue.getItemProperty("duration").setValue(durationStr);
                        String definition = videoItem.get("contentDetails").get("definition").getTextValue();
                        newValue.getItemProperty("definition").setValue(definition);
                    }
                } catch (Exception e) {
                    log.error("Failed to parse the video duration.", e);
                }
            }
        }
    });

    ddLine.addComponent(fetchButton);
    ddLine.setWidth(100, Unit.PERCENTAGE);
    ddLine.setHeight(-1, Unit.PIXELS);
    ddLine.setComponentAlignment(fetchButton, Alignment.BOTTOM_RIGHT);
    root.addComponent(ddLine);

    PropertysetItem item = (PropertysetItem) getPropertyDataSource().getValue();
    root.addComponent(createEntryComponent("default", item), root.getComponentCount() - 1);
    root.addComponent(createEntryComponent("standard", item), root.getComponentCount() - 1);
    root.addComponent(createEntryComponent("medium", item), root.getComponentCount() - 1);
    root.addComponent(createEntryComponent("high", item), root.getComponentCount() - 1);
    root.addComponent(createEntryComponent("maxres", item), root.getComponentCount() - 1);
}

From source file:com.mgmtp.jfunk.common.util.ResourceLoader.java

/**
 * Loads a resource as {@link InputStream}.
 * //  w  w  w.  j a va 2s.co m
 * @param resource
 *            The resource to be loaded. If {@code baseDir} is not {@code null}, it is loaded
 *            relative to {@code baseDir}.
 * @return The stream
 */
public static InputStream getInputStream(final File resource) throws IOException {
    if (resource.exists()) {
        return new FileInputStream(resource);
    }
    LOG.info("Could not find file '" + resource.getAbsolutePath()
            + "' in the file system. Trying to load it from the classpath...");

    String path = FilenameUtils.separatorsToUnix(resource.getPath());
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    InputStream is = cl.getResourceAsStream(path);

    if (is == null) {
        if (path.startsWith("/")) {
            LOG.info("Could not find file '" + resource
                    + " in the file system. Trying to load it from the classpath without the leading slash...");
            is = cl.getResourceAsStream(path.substring(1));
        }

        if (is == null) {
            // If configs are to be loaded from the classpath, we also try it directly
            // stripping of the config directory
            String configDir = new File(getConfigDir()).getName();
            if (path.startsWith(configDir)) {
                is = cl.getResourceAsStream(StringUtils.substringAfter(path, configDir + '/'));
            }
        }

        if (is == null) {
            throw new FileNotFoundException("Could not load file '" + resource + "'");
        }
    }

    return is;
}

From source file:com.threewks.thundr.route.cors.CorsFilter.java

/**
 * Examines the request for the Origin header. If the origin header is
 * present (ignoring protocol) in the set of supported origins, the header
 * value will be returned (signifying permission), otherwise null is returned.
 * // www.  j a v a2 s  .c o  m
 * @param req
 * @param origins
 * @return
 */
protected String origin(HttpServletRequest req, List<String> origins) {
    String originHeader = req.getHeader(Header.Origin);
    String origin = StringUtils.substringAfter(originHeader, "//");
    return origins.contains(origin) ? originHeader : null;
}

From source file:eu.openanalytics.rsb.component.JobsResource.java

/**
 * Handles a multi-part form job upload.
 * //w w w .j  a v  a 2s  .com
 * @param parts
 * @param httpHeaders
 * @param uriInfo
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
@POST
@Consumes(Constants.MULTIPART_CONTENT_TYPE)
// force content type to plain XML and JSON (browsers choke on subtypes)
@Produces({ Constants.XML_CONTENT_TYPE, Constants.JSON_CONTENT_TYPE })
public Response handleMultipartFormJob(final List<Attachment> parts, @Context final HttpHeaders httpHeaders,
        @Context final UriInfo uriInfo) throws URISyntaxException, IOException {
    String applicationName = null;
    final Map<String, Serializable> jobMeta = new HashMap<String, Serializable>();

    for (final Attachment part : parts) {
        final String partName = getPartName(part);
        if (StringUtils.equals(partName, Constants.APPLICATION_NAME_HTTP_HEADER)) {
            applicationName = part.getObject(String.class);
        } else if (StringUtils.startsWith(partName, Constants.RSB_META_HEADER_HTTP_PREFIX)) {
            final String metaName = StringUtils.substringAfter(partName, Constants.RSB_META_HEADER_HTTP_PREFIX);
            final String metaValue = part.getObject(String.class);
            if (StringUtils.isNotEmpty(metaValue)) {
                jobMeta.put(metaName, metaValue);
            }
        }
    }

    final String finalApplicationName = applicationName;

    return handleNewJob(finalApplicationName, httpHeaders, uriInfo, new JobBuilder() {
        @Override
        public AbstractJob build(final String applicationName, final UUID jobId,
                final GregorianCalendar submissionTime) throws IOException {

            final MultiFilesJob job = new MultiFilesJob(Source.REST, applicationName, getUserName(), jobId,
                    submissionTime, jobMeta);

            for (final Attachment part : parts) {
                if (StringUtils.equals(getPartName(part), Constants.JOB_FILES_MULTIPART_NAME)) {
                    final InputStream data = part.getDataHandler().getInputStream();
                    if (data.available() == 0) {
                        // if the form is submitted with no file attached, we get
                        // an empty part
                        continue;
                    }
                    MultiFilesJob.addDataToJob(part.getContentType().toString(), getPartFileName(part), data,
                            job);
                }
            }

            return job;
        }
    });
}

From source file:com.netflix.imfutility.conversion.executor.ConversionOperationParser.java

private String addQuotes(String param) {
    if (!param.contains(" ") && !param.contains("\n") && !param.contains("\r")) {
        return param;
    }/*from   w w w .  j  a  v a 2  s.  c o  m*/
    if (!param.contains("=")) {
        return addQuotesIfNeeded(param);
    }
    String subParam = StringUtils.substringAfter(param, "=");
    String quotedSubParam = addQuotesIfNeeded(subParam);
    return StringUtils.substringBefore(param, "=") + "=" + quotedSubParam;
}

From source file:net.eledge.android.europeana.search.SearchController.java

public List<FacetItem> getBreadcrumbs(Context context) {
    List<FacetItem> breadcrumbs = new ArrayList<>();
    FacetItem crumb;/*www.  j  a  v  a  2  s  .  c  o  m*/
    for (String term : terms) {
        crumb = new FacetItem();
        crumb.itemType = FacetItemType.BREADCRUMB;
        crumb.facetType = FacetType.TEXT;
        crumb.description = term;
        crumb.facet = term;
        if (StringUtils.contains(term, ":")) {
            FacetType type = FacetType.safeValueOf(StringUtils.substringBefore(term, ":"));
            if (type != null) {
                crumb.facetType = type;
                crumb.description = StringUtils
                        .capitalize(StringUtils.lowerCase(GuiUtils.getString(context, type.resId))) + ":"
                        + type.createFacetLabel(context, StringUtils.substringAfter(term, ":"));
            }
        }
        breadcrumbs.add(crumb);
    }
    return breadcrumbs;
}

From source file:me.utils.excel.ImportExcelme.java

/**
 * ??//  ww  w  .  ja  va  2  s .  c o m
 * @param cls 
 */
public <E> List<E> getDataList(Class<E> cls, List<Zbx> zbxList) throws Exception {
    String title = (String) getMergedRegionValue(sheet, 0, 1);//?
    String tbDw = StringUtils.substringAfter((String) getMergedRegionValue(sheet, 1, 0), "");//
    Date tbDate = DateUtils
            .parseDate((StringUtils.substringAfter((String) getMergedRegionValue(sheet, 1, 4), ":")));//5?
    //      Date tbDate = DateUtil.getJavaDate(Double.valueOf(StringUtils.substringAfter((String)getMergedRegionValue(sheet, 1, 4), ":"))) ;//5?

    Map<String, String> map = Maps.newHashMap();
    for (Zbx zbx : zbxList) {
        map.put(zbx.getPropertyText(), zbx.getPropertyName());
    }
    List<String> propertyNames = Lists.newArrayList();
    for (int i = 0; i < this.getLastCellNum(); i++) {//?header  ?
        Row row = this.getRow(this.getHeaderRowNum());
        Object val = this.getCellValue(row, i);
        String propertyName = map.get(val);
        if (StringUtils.isEmpty(propertyName)) {
            throw new BusinessException("" + val + "?");
        }
        propertyNames.add(propertyName);
    }
    //log.debug("Import column count:"+annotationList.size());
    // Get excel data
    List<E> dataList = Lists.newArrayList();
    for (int i = this.getDataRowNum(); i <= this.getLastDataRowNum(); i++) {
        E e = (E) cls.newInstance();

        int column = 0;
        Row row = this.getRow(i);
        StringBuilder sb = new StringBuilder();
        for (String propertyName : propertyNames) {
            Object val = this.getCellValue(row, column++);//string 
            if (val != null) {
                // Get param type and type cast
                Class<?> valType = Reflections.getAccessibleField(e, propertyName).getType();

                check(e, propertyName, val, i, column);
                //log.debug("Import value type: ["+i+","+column+"] " + valType);
                try {
                    if (valType == String.class) {
                        String s = String.valueOf(val.toString());
                        if (StringUtils.endsWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            val = String.valueOf(val.toString());
                        }
                    } else if (valType == Integer.class) {
                        val = Double.valueOf(val.toString()).intValue();
                    } else if (valType == Long.class) {
                        val = Double.valueOf(val.toString()).longValue();
                    } else if (valType == Double.class) {
                        val = Double.valueOf(val.toString());
                    } else if (valType == Float.class) {
                        val = Float.valueOf(val.toString());
                    } else if (valType == Date.class) {
                        //                     val = DateUtil.getJavaDate((Double)val);
                        val = DateUtils.parseDate(val.toString());
                    } else {//?  wjmany-to-one etc.
                    }
                } catch (Exception ex) {
                    log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
                    val = null;
                }
                // set entity value
                Reflections.invokeSetter(e, propertyName, val);
            }
            sb.append(val + ", ");
        }
        Reflections.invokeSetter(e, "title", title);
        Reflections.invokeSetter(e, "tbDw", tbDw);
        Reflections.invokeSetter(e, "tbDate", tbDate);
        dataList.add(e);
        log.debug("Read success: [" + i + "] " + sb.toString());
    }
    return dataList;
}