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

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

Introduction

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

Prototype

public static String trim(final String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String, handling null by returning null .

The String is trimmed using String#trim() .

Usage

From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivitySyslogEventParser.java

/**
 * Process Syslog message based on RFC 5424.
 *
 * @param facility//from w w w  . j  av a  2s . c  om
 *            Syslog facility name
 * @param event
 *            Syslog message
 * @param dataMap
 *            log entry fields map to update
 */
protected static void processRFC3164(String facility, SyslogServerEventIF event, Map<String, Object> dataMap) {
    Map<String, Object> map = parseAttributes(event);
    String serverName = map.get(ATTR_SERVER_NAME).toString();
    String appName = map.get(ATTR_APPL_NAME).toString();
    Long pid = (Long) map.get(ATTR_APPL_PID);

    dataMap.put(Tag.name(), new String[] { serverName, appName });
    SyslogUtils.assignPid(String.valueOf(pid), dataMap);
    dataMap.put(ResourceName.name(), appName);
    dataMap.put(EventName.name(), facility);

    // set the appropriate source
    dataMap.put(ApplName.name(), appName);
    dataMap.put(ServerName.name(), serverName);

    dataMap.put(Message.name(), StringUtils.trim(event.getMessage()));
}

From source file:com.adguard.android.service.FilterServiceImpl.java

@Override
public void applyNewSettings() {
    setShowUsefulAds(preferencesService.isShowUsefulAds());

    List<String> rules = getAllEnabledRules(true);
    Set<String> userRules = getUserRules();
    if (!userRules.isEmpty()) {
        for (String userRule : userRules) {
            userRule = StringUtils.trim(userRule);

            if (validateRuleText(userRule)) {
                rules.add(userRule);//from   w  w  w  .  j a  v a2 s . c  o m
            }
        }
    }

    cachedFilterRuleCount = rules.size();

    try {
        LOG.info("Saving {} filters...", cachedFilterRuleCount);
        FileUtils.writeLines(new File(context.getFilesDir().getAbsolutePath() + "/filters.txt"), rules);
        preferencesService.setFilterRuleCount(cachedFilterRuleCount);
        enableContentBlocker(context);
    } catch (IOException e) {
        LOG.warn("Unable to save filters to file!!!", e);
    }
}

From source file:ch.cyberduck.core.Host.java

/**
 * @param defaultpath The path to change the working directory to upon connecting
 *///from ww  w  .  j a  v  a2s.c o  m
public void setDefaultPath(final String defaultpath) {
    this.defaultpath = StringUtils.isBlank(defaultpath) ? null : StringUtils.trim(defaultpath);
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Set<UpnpIgdServiceReference> parseServiceReferences(Map<UpnpIgdDevice, byte[]> rootBuffers) {
    Set<UpnpIgdServiceReference> services = new HashSet<>();
    for (Entry<UpnpIgdDevice, byte[]> rootBufferEntry : rootBuffers.entrySet()) {
        try {/*from   w  w  w  .  j  a  v  a 2s. c om*/
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new ByteArrayInputStream(rootBufferEntry.getValue()));

            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList serviceNodes = (NodeList) xPath.compile(".//service").evaluate(doc,
                    XPathConstants.NODESET);

            for (int i = 0; i < serviceNodes.getLength(); i++) {
                Node serviceNode = serviceNodes.item(i);

                String serviceType = StringUtils.trim(xPath.compile("serviceType").evaluate(serviceNode));
                String serviceId = StringUtils.trim(xPath.compile("serviceId").evaluate(serviceNode));
                String controlUrl = StringUtils.trim(xPath.compile("controlURL").evaluate(serviceNode));
                //String eventSubUrl = StringUtils.trim(xPath.compile("eventSubURL").evaluate(serviceNode));
                String scpdUrl = StringUtils.trim(xPath.compile("SCPDURL").evaluate(serviceNode));

                UpnpIgdServiceReference service = new UpnpIgdServiceReference(rootBufferEntry.getKey(),
                        serviceType, serviceId, controlUrl, scpdUrl);
                services.add(service);
            }
        } catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException e) { // NOPMD
            // do nothing, just skip
        }
    }
    return services;
}

From source file:ching.icecreaming.action.ResourceDescriptors.java

@Action(value = "resource-descriptors", results = { @Result(name = "success", location = "json.jsp") })
public String execute() throws Exception {
    int int1 = 401, int0 = 0;
    String string1 = null;// w ww  .  ja  va  2s .  c  om
    URL url1 = null;
    URI uri1 = null;
    HttpGet httpGet1 = null;
    HttpResponse httpResponse1 = null;
    HttpEntity httpEntity1 = null;
    HttpPost httpPost1 = null;
    HttpHost httpHost1 = null;
    DefaultHttpClient httpClient1 = null;
    File file1 = null;
    InputStream inputStream1 = null;
    OutputStream outputStream1 = null;
    BeanComparator beanComparator1 = null;
    List<Map<String, Object>> list1 = null, list2 = null;
    Map<String, Object> map1 = null;
    Object object1 = null;
    int toIndex = rows * page;
    int fromIndex = toIndex - rows;
    GridModel1 jsonObject1 = null;
    Gson gson = null;
    Long long1 = -1L;
    java.util.Date date1 = null;
    URIBuilder uriBuilder1 = null;
    Node node1 = null;
    Element element1 = null;
    NodeList nodeList1 = null;
    Document document1 = null;
    DocumentBuilder documentBuilder1 = null;
    DocumentBuilderFactory documentBuilderFactory1 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;

    try {
        if (StringUtils.isNotEmpty(sid) && StringUtils.isNotEmpty(uid) && StringUtils.isNotEmpty(pid)) {
            sid = new String(Base64.decodeBase64(sid.getBytes()));
            uid = new String(Base64.decodeBase64(uid.getBytes()));
            pid = new String(Base64.decodeBase64(pid.getBytes()));
            httpClient1 = new DefaultHttpClient();
            url1 = new URL(sid);
            uriBuilder1 = new URIBuilder(sid);
            uriBuilder1.setParameter("j_username", uid);
            uriBuilder1.setParameter("j_password", pid);
            uriBuilder1.setPath(url1.getPath() + "/rest/resources" + urlString);
            uriBuilder1.setUserInfo(uid, pid);
            uri1 = uriBuilder1.build();
            httpGet1 = new HttpGet(uri1);
            httpResponse1 = httpClient1.execute(httpGet1);
            int1 = httpResponse1.getStatusLine().getStatusCode();
            if (int1 == HttpStatus.SC_OK) {
                httpEntity1 = httpResponse1.getEntity();
                inputStream1 = httpResponse1.getEntity().getContent();
                if (inputStream1 != null) {
                    documentBuilderFactory1 = DocumentBuilderFactory.newInstance();
                    documentBuilder1 = documentBuilderFactory1.newDocumentBuilder();
                    document1 = documentBuilder1.parse(inputStream1);
                    document1.getDocumentElement().normalize();
                    nodeList1 = document1.getElementsByTagName("resourceDescriptor");
                    int1 = nodeList1.getLength();
                    list1 = new ArrayList<Map<String, Object>>();
                    for (int0 = 0; int0 < int1; int0++) {
                        node1 = nodeList1.item(int0);
                        if (node1.getNodeType() == Node.ELEMENT_NODE) {
                            element1 = (Element) node1;
                            map1 = new HashMap<String, Object>();
                            map1.put("wsType", element1.getAttribute("wsType"));
                            map1.put("uriString", element1.getAttribute("uriString"));
                            string1 = getTagValue("label", element1);
                            map1.put("label1", StringUtils.defaultString(string1));
                            string1 = getTagValue("description", element1);
                            map1.put("description", StringUtils.defaultString(string1));
                            string1 = getTagValue("creationDate", element1);
                            long1 = (string1 == null) ? -1L
                                    : NumberUtils.toLong(StringUtils.trim(string1), -1L);
                            if (long1 > 0) {
                                if (StringUtils.isNotBlank(timeZone1)) {
                                    dateTime1 = new org.joda.time.DateTime(long1);
                                    dateTime2 = dateTime1.withZone(DateTimeZone.forID(timeZone1));
                                    date1 = dateTime2.toLocalDateTime().toDate();
                                } else {
                                    date1 = new java.util.Date(long1);
                                }
                            } else {
                                date1 = null;
                            }
                            map1.put("creationDate", date1);
                            map1.put("type1", getText(element1.getAttribute("wsType")));
                            list1.add(map1);
                        }
                    }
                }
                EntityUtils.consume(httpEntity1);
            }
        }
    } catch (UnsupportedEncodingException | URISyntaxException | ParserConfigurationException
            | SAXException exception1) {
        exception1.printStackTrace();
        return ERROR;
    } catch (org.apache.http.conn.HttpHostConnectException | java.net.NoRouteToHostException
            | java.net.MalformedURLException | java.net.UnknownHostException exception1) {
        exception1.printStackTrace();
        return ERROR;
    } catch (IOException exception1) {
        httpGet1.abort();
        exception1.printStackTrace();
        return ERROR;
    } finally {
        if (httpClient1 != null)
            httpClient1.getConnectionManager().shutdown();
        if (list1 != null) {
            records = list1.size();
            if (list1.size() > 0) {
                if (StringUtils.isNotEmpty(sidx)) {
                    if (StringUtils.equals(sord, "desc")) {
                        beanComparator1 = new BeanComparator(sidx,
                                new ReverseComparator(new ComparableComparator()));
                    } else {
                        beanComparator1 = new BeanComparator(sidx);
                    }
                    Collections.sort(list1, beanComparator1);
                }
                if (StringUtils.isNotBlank(searchField) && StringUtils.isNotEmpty(searchOper)) {
                    Iterator iterator1 = list1.iterator();
                    while (iterator1.hasNext()) {
                        map1 = (Map<String, Object>) iterator1.next();
                        for (Map.Entry<String, Object> entry1 : map1.entrySet()) {
                            if (StringUtils.equals(entry1.getKey(), searchField)) {
                                object1 = entry1.getValue();
                                if (searchFilter(searchField, searchOper, searchString, object1))
                                    iterator1.remove();
                                break;
                            }
                        }
                    }
                    records = list1.size();
                }
                if (toIndex > records)
                    toIndex = records;
                if (fromIndex > toIndex) {
                    fromIndex = toIndex - rows;
                    if (fromIndex < 0)
                        fromIndex = 0;
                }
                if (list1.size() > 0 && fromIndex >= 0 && toIndex <= list1.size() && fromIndex <= toIndex)
                    list2 = list1.subList(fromIndex, toIndex);

            }
            total = (int) Math.ceil((double) records / (double) rows);
            if (page > total)
                page = total;
            jsonObject1 = new GridModel1(rows, page, sord, sidx, searchField, searchString, searchOper, total,
                    records, id, list2);
            gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();
            jsonData = gson.toJson(jsonObject1);
        }
        IOUtils.closeQuietly(inputStream1);
    }
    return SUCCESS;
}

From source file:com.ottogroup.bi.asap.pipeline.MicroPipeline.java

/**
 * Submits the provided {@link OperatorExecutor} to the pipeline instance
 * @param operatorExecutor/*  ww  w .j  a v  a  2  s  . c om*/
 * @throws RequiredInputMissingException
 * @throws ComponentAlreadySubmittedException
 */
public void submitOperatorExecutor(final OperatorExecutor operatorExecutor)
        throws RequiredInputMissingException, ComponentAlreadySubmittedException {

    ///////////////////////////////////////////////////////////////////
    // validate input
    if (operatorExecutor == null)
        throw new RequiredInputMissingException("Missing required input for 'operatorExecutor'");
    if (StringUtils.isBlank(operatorExecutor.getOperatorId()))
        throw new RequiredInputMissingException("Missing required input for operator identifier");
    //
    ///////////////////////////////////////////////////////////////////

    // normalize identifier to lower case
    String oid = StringUtils.lowerCase(StringUtils.trim(operatorExecutor.getOperatorId()));
    if (this.operatorExecutors.containsKey(oid))
        throw new ComponentAlreadySubmittedException("Component '" + operatorExecutor.getOperatorId()
                + "' already submitted to pipeline '" + id + "'");

    // add operator executor to internal map and submit it to executor service
    this.operatorExecutors.put(oid, operatorExecutor);
    this.executorService.submit(operatorExecutor);

    if (logger.isDebugEnabled())
        logger.debug("operator executor submitted [pid=" + id + ", oid=" + oid + ", mb="
                + operatorExecutor.getMailbox() + "]");
}

From source file:com.ottogroup.bi.spqr.pipeline.MicroPipelineManagerTest.java

/**
 * Test case for {@link MicroPipelineManager#hasPipeline(String)} with existing identifier 
 *///from ww w . ja  v  a  2s  .  co m
@Test
public void testHasPipeline_withExistingId() throws Exception {
    MicroPipelineConfiguration cfg = new MicroPipelineConfiguration();
    cfg.setId("testExecutePipeline_withValidConfiguration");

    MicroPipeline pipeline = Mockito.mock(MicroPipeline.class);
    Mockito.when(pipeline.getId()).thenReturn(cfg.getId());

    MicroPipelineFactory factory = Mockito.mock(MicroPipelineFactory.class);
    Mockito.when(factory.instantiatePipeline(cfg, executorService)).thenReturn(pipeline);

    MicroPipelineManager manager = new MicroPipelineManager("id", factory, executorService);

    Assert.assertEquals("Values must be equal", StringUtils.lowerCase(StringUtils.trim(cfg.getId())),
            manager.executePipeline(cfg));
    Assert.assertEquals("Values must be equal", 1, manager.getNumOfRegisteredPipelines());

    Mockito.verify(factory).instantiatePipeline(cfg, executorService);

    Assert.assertTrue("Pipeline exists", manager.hasPipeline(cfg.getId()));
}

From source file:com.orange.ocara.ui.activity.EditAuditActivity.java

protected Auditor getAuthor() {
    Auditor author = currentAuthor;/*from w  w  w  .ja v a 2 s . c o  m*/

    if (author == null) {
        Matcher matcher = AUTHOR_PATTERN.matcher(this.author.getText());
        if (matcher.find()) {
            author = new Auditor();
            author.setUserName(StringUtils.trim(matcher.group(0)));
        }
    }

    return author;
}

From source file:eu.semlibproject.annotationserver.AdminDataHelper.java

public boolean areEmailsValid(String receivers) {
    String expression = "([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\\.)+[A-Z]{2,6},?)*";
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    if (receivers.contains(";")) {
        for (String receiver : receivers.split(";")) {
            CharSequence inputStr = StringUtils.trim(receiver);
            Matcher matcher = pattern.matcher(inputStr);
            if (!matcher.matches())
                return false;
        }//from  ww  w. ja  v a  2  s  . c o  m
        return true;
    } else {
        CharSequence inputStr = StringUtils.trim(receivers);
        Matcher matcher = pattern.matcher(inputStr);
        return matcher.matches();
    }
}

From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivitySyslogEventParser.java

/**
 * Process Syslog message based on RFC 5424.
 *
 * @param facility/*from   w  w w. jav  a2 s  .c  o m*/
 *            Syslog facility name
 * @param sEvent
 *            Syslog structured message event
 * @param dataMap
 *            log entry fields map to update
 */
protected static void processRFC5424(String facility, StructuredSyslogServerEvent sEvent,
        Map<String, Object> dataMap) {
    // RFC 5424
    StructuredSyslogMessage sMessage = sEvent.getStructuredMessage();
    String msgId = sMessage.getMessageId();
    dataMap.put(EventName.name(), facility);
    dataMap.put(ResourceName.name(), sEvent.getApplicationName());
    dataMap.put(Tag.name(), new String[] { facility, sEvent.getHost(), sEvent.getApplicationName(), msgId });
    // if (StringUtils.isNotEmpty(msgId)) {
    // dataMap.put(TrackingId.name(), msgId);
    // }
    SyslogUtils.assignPid(
            StringUtils.isEmpty(sEvent.getProcessId()) ? sMessage.getProcId() : sEvent.getProcessId(), dataMap);

    // set the appropriate source
    dataMap.put(ApplName.name(), sEvent.getApplicationName());
    dataMap.put(ServerName.name(), sEvent.getHost());
    dataMap.put(Message.name(), StringUtils.trim(sMessage.getMessage()));

    // process structured event attributes into snapshot
    extractStructuredData(sMessage, dataMap);

    // extract name=value pairs if available
    SyslogUtils.extractVariables(sMessage.getMessage(), dataMap);
}