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

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

Introduction

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

Prototype

public static String trim(String str) 

Source Link

Document

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

Usage

From source file:ml.shifu.shifu.core.dvarsel.wrapper.ValidationConductorTest.java

public void addRecordIntoTrainDataSet(ModelConfig modelConfig, List<ColumnConfig> columnConfigList,
        TrainingDataSet trainingDataSet, String record) {
    String[] fields = CommonUtils.split(record, modelConfig.getDataSetDelimiter());

    int targetColumnId = CommonUtils.getTargetColumnNum(columnConfigList);
    String tag = StringUtils.trim(fields[targetColumnId]);

    double[] inputs = new double[trainingDataSet.getDataColumnIdList().size()];
    double[] ideal = new double[1];

    double significance = CommonConstants.DEFAULT_SIGNIFICANCE_VALUE;

    ideal[0] = (modelConfig.getPosTags().contains(tag) ? 1.0d : 0.0d);

    int i = 0;/*from  w  ww  . j  a v a2  s.  c o m*/
    for (Integer columnId : trainingDataSet.getDataColumnIdList()) {
        List<Double> normVals = Normalizer.normalize(columnConfigList.get(columnId), fields[columnId]);
        for (Double normVal : normVals) {
            inputs[i++] = normVal;
        }
    }

    trainingDataSet.addTrainingRecord(new TrainingRecord(inputs, ideal, significance));
}

From source file:com.naver.jr.study.bo.sesame.SesameBOImpl.java

@Override
public SesameSeasonVideo getSeasonVideo(int seasonVideoNo) throws IOException, SAXException, SQLException {
    SesameSeasonVideo seasonVideo = sesameSeasonVideoDAO.selectSeasonVideo(seasonVideoNo);
    if (seasonVideo == null) {
        return seasonVideo;
    }// w ww .ja va  2s .  c o m

    if (StringUtils.equals(JrCommonUtil.getMobileDevice(), "iphone")) {
        String vid = seasonVideo.getVideoId();
        seasonVideo.setVideoId(videoRemoteBO.getVideoId(vid, "270P_480_500_64_1"));
    }

    seasonVideo.setInKey(JrCommonUtil.createInKey(StringUtils.trim(seasonVideo.getVideoId())));
    return seasonVideo;
}

From source file:com.qatickets.service.UserService.java

@Transactional(readOnly = false)
public UserProfile saveOrUpdateUser(UserProfile currentUser, String userName, String email, int timezone,
        int userId) throws Exception {

    UserProfile profile = null;/* w  ww .j a v  a  2  s. c  om*/

    userName = spamService.clean(StringUtils.trim(userName), 32);
    email = spamService.clean(StringUtils.trim(email), 128);

    if (false == this.isValidEmail(email)) {
        throw new EmailNotValidException();
    }

    if (userId == 0) {

        // new user
        profile = new UserProfile();
        profile.setDate(new Date());

        final String password = RandomStringUtils.randomAlphanumeric(DEFAULT_PASSWORD_LENGTH);

        profile.setPassword(password);

    } else {

        profile = this.findById(userId);

        if (profile == null) {
            throw new ProfileNotFoundException();
        }

        // if not the same user or owner, quit
        if (false == currentUser.equals(profile)) {
            throw new ProfileNotFoundException();
        }

    }

    if (profile.isNew() || false == profile.getEmail().equals(email)) {

        log.debug("Email was asked to changed/set to: " + email + " for " + profile);

        if (this.isEmailRegistered(email)) {
            log.debug("The e-mail address is used by other user");
            throw new EmailAlreadyRegisteredException();
        }

        profile.setEmail(email);

    }

    profile.setName(userName);
    profile.setTimezone(timezone);

    this.save(profile);

    // TODO send email to both owner and new user with the new password

    log.debug("User saved: " + profile);

    return profile;

}

From source file:com.openteach.diamond.service.route.WeightRuleParser.java

/**
 * ? config?????// w ww .  j av a2  s  .c o m
 * @param serviceUniqueName ???
 * @param rule ?: 
 *      <service>
 *         <name>com.*</name>
 *         <ipweights>
 *            <ipweight>
 *               <ip></ip>
 *               <weight></weight>
 *            </ipweight>
 *         </ipweights>
 *      </service>
 *  XXX TODO throw exception
 * @return
 * @throws RuleParseException
 */
public WeightRule parse(String rule) throws RuleParseException {

    if (StringUtils.isBlank(rule)) {
        // allowed empty weight rule of service
        return null;
    }

    InputStream stream = null;
    try {
        Document doc = null;
        try {
            stream = new ByteArrayInputStream(rule.getBytes());
            doc = db.parse(stream);
        } catch (SAXException e) {
            throw new RuleParseException(String.format("Parse rule failed, wrong xml format, rule:%s", rule));
        } catch (IOException e) {
            throw new RuleParseException("OMG, Not possible", e);
        }

        WeightRule w = new WeightRule();
        Element root = doc.getDocumentElement();
        NodeList nameNodeList = root.getElementsByTagName(NAME);
        if (null == nameNodeList || 1 != nameNodeList.getLength()) {
            throw new RuleParseException(
                    String.format("Parse rule failed, rule must has only one <name> tag, rule:%s", rule));
        }
        // name
        Node nameNode = nameNodeList.item(0);
        w.setServiceName(StringUtils.trim(nameNode.getTextContent()));
        if (StringUtils.isBlank(w.getServiceName())) {
            throw new RuleParseException(
                    String.format("Parse rule failed, <name> tag must not be empty, rule:%s", rule));
        }

        NodeList ipWeightsList = root.getElementsByTagName(IPWEIGHTS);
        if (null == ipWeightsList || ipWeightsList.getLength() != 1) {
            throw new RuleParseException(
                    String.format("Parse rule failed, rule must has only one <ipweights> tag, rule:%s", rule));
        }

        // ipweights
        Node ipWeightsNode = ipWeightsList.item(0);
        NodeList ipWeightNodeList = ipWeightsNode.getChildNodes();
        if (null == ipWeightNodeList || 0 == ipWeightNodeList.getLength()) {
            throw new RuleParseException(String.format(
                    "Parse rule failed, tag <ipweights> must has one or more child tag <ipweight>, rule:%s",
                    rule));
        }

        for (int i = 0; i < ipWeightNodeList.getLength(); i++) {
            String ip = null;
            String weight = null;
            Node ipWeightNode = ipWeightNodeList.item(i);
            NodeList ipAndWeightList = ipWeightNode.getChildNodes();
            if (null == ipAndWeightList || 2 != ipAndWeightList.getLength()) {
                throw new RuleParseException(String.format(
                        "Parse rule failed, tag <ipweight> must has only one child tag <ip> and only one <weight>, rule:%s",
                        rule));
            }
            for (int k = 0; k < ipAndWeightList.getLength(); k++) {
                Node ipAndWeightNode = ipAndWeightList.item(k);
                if (IP.equalsIgnoreCase(ipAndWeightNode.getNodeName())) {
                    ip = ipAndWeightNode.getTextContent();
                } else if (WEIGHT.equalsIgnoreCase(ipAndWeightNode.getNodeName())) {
                    weight = ipAndWeightNode.getTextContent();
                }
            }
            if (StringUtils.isBlank(ip) || StringUtils.isBlank(weight)) {
                throw new RuleParseException(String.format(
                        "Parse rule failed, tag <ipweight> must has only one child tag <ip> and only one <weight>, rule:%s",
                        rule));
            }

            try {
                Integer tmp = Integer.valueOf(weight);
                if (tmp <= 0) {
                    throw new RuleParseException(String
                            .format("Parse rule failed, weight must be big then 0 integer, rule:%s", rule));
                }
                w.addIPAndWeight(ip, tmp);
            } catch (NumberFormatException e) {
                throw new RuleParseException(
                        String.format("Parse rule failed, weight must be big then 0 integer, rule:%s", rule));
            }
        }
        return w;
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                //ignore
            }
        }
    }
}

From source file:com.alibaba.otter.manager.biz.monitor.impl.DelayStatRuleMonitor.java

private boolean checkDelayTime(AlarmRule rule, Long delayTime) {

    if (!inPeriod(rule)) {
        return false;
    }//from  www.  j  a  va2 s .  c o  m

    String matchValue = rule.getMatchValue();
    matchValue = StringUtils.substringBeforeLast(matchValue, "@");
    Long maxDelayTime = Long.parseLong(StringUtils.trim(matchValue));
    if (delayTime >= maxDelayTime * 1000) {
        sendAlarm(rule, String.format(DELAY_TIME_MESSAGE, rule.getPipelineId(), delayTime));
        return true;
    }
    return false;
}

From source file:com.htmlhifive.tools.jslint.engine.download.AbstractDownloadEngineSupport.java

@Override
public EngineInfo getEngineInfo(IProgressMonitor monitor) throws IOException {
    IProgressMonitor actualMonitor = monitor;
    if (monitor == null) {
        actualMonitor = new NullProgressMonitor();
    }/*from  w w  w.  j a  v  a2s  .co  m*/
    actualMonitor.setTaskName(Messages.T0009.getText());
    HttpClient client = createHttpClient(getEngineSourceUrl());
    HttpMethod getMethod = new GetMethod(getEngineSourceUrl());
    int result = client.executeMethod(getMethod);
    if (result != HttpStatus.SC_OK) {
        // TODO 
        return null;
    }
    StringBuilder licenseSb = new StringBuilder();
    StringBuilder rawSource = new StringBuilder();
    Header header = getMethod.getResponseHeader("Content-Length");
    int content = Integer.valueOf(header.getValue());
    actualMonitor.beginTask(Messages.T0010.getText(), content);
    BufferedReader reader = new BufferedReader(new InputStreamReader(getMethod.getResponseBodyAsStream()));
    String temp = reader.readLine();
    int progress = 0;
    while (!isEndLicenseLine(temp)) {
        progress += temp.length();
        actualMonitor.subTask(Messages.T0011.format(progress, content));
        actualMonitor.worked(temp.length());
        rawSource.append(temp);
        temp = StringUtils.trim(temp);
        temp = StringUtils.substring(temp, 2);
        temp = StringUtils.trim(temp);
        licenseSb.append(temp);
        licenseSb.append(System.getProperty("line.separator"));
        rawSource.append(System.getProperty("line.separator"));
        temp = reader.readLine();
    }
    EngineInfo info = new EngineInfo();
    info.setLicenseStr(licenseSb.toString());

    while ((temp = reader.readLine()) != null) {
        progress += temp.length();
        actualMonitor.subTask(Messages.T0011.format(progress, content));
        actualMonitor.worked(temp.length());
        rawSource.append(temp);
        rawSource.append(System.getProperty("line.separator"));
    }
    info.setMainSource(rawSource.toString());
    monitor.done();
    return info;
}

From source file:com.doculibre.constellio.wicket.panels.admin.synonyms.AddEditSynonymsPanel.java

public AddEditSynonymsPanel(String id, SynonymList synonymList) {
    super(id, true);
    this.synonymListModel = new ReloadableEntityModel<SynonymList>(synonymList);

    Form form = getForm();/*from  w  w w.j  av  a  2 s.c  om*/
    form.setModel(new CompoundPropertyModel(synonymListModel));

    IModel synonymsFieldModel = new Model() {
        @Override
        public Object getObject() {
            StringBuffer sb = new StringBuffer();
            SynonymList synonymList = synonymListModel.getObject();
            if (synonymList != null) {
                for (Iterator<String> it = synonymList.getSynonyms().iterator(); it.hasNext();) {
                    String synonym = (String) it.next();
                    sb.append(synonym);
                    if (it.hasNext()) {
                        sb.append("\n");
                    }
                }
            }
            return sb.toString();
        }

        @Override
        public void setObject(Serializable object) {
            SynonymList synonymList = synonymListModel.getObject();
            synonymList.getSynonyms().clear(); // Reset
            StringTokenizer st = new StringTokenizer((String) object, "\n");
            while (st.hasMoreTokens()) {
                String synonym = (String) st.nextToken();
                synonymList.getSynonyms().add(StringUtils.trim(synonym));
            }
        }
    };
    TextArea synonyms = new TextArea("synonyms", synonymsFieldModel);
    synonyms.setOutputMarkupId(true);
    synonyms.setRequired(true);
    form.add(synonyms);
}

From source file:jp.ikedam.jenkins.plugins.viewcopy_builder.SetDescriptionOperation.java

/**
 * @param doc//from w w w . ja va2s.  c  o  m
 * @param env
 * @param logger
 * @return
 * @see jp.ikedam.jenkins.plugins.viewcopy_builder.ViewcopyOperation#perform(org.w3c.dom.Document, hudson.EnvVars, java.io.PrintStream)
 */
@Override
public Document perform(Document doc, EnvVars env, PrintStream logger) {
    Node descNode;
    try {
        descNode = getNode(doc, "/*/description");
    } catch (XPathExpressionException e) {
        e.printStackTrace(logger);
        return null;
    }

    if (descNode == null) {
        // includeRegex is not exist.
        // create new one.
        descNode = doc.createElement("description");
        doc.getDocumentElement().appendChild(descNode);
    }

    String description = (getDescription() != null) ? StringUtils.trim(env.expand(getDescription())) : "";

    descNode.setTextContent(description);
    logger.println(String.format("Set description to:\n%s", description));

    return doc;
}

From source file:com.xx_dev.apn.socks.local.FakeHttpClientDecoder.java

protected void _decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (this.state()) {
    case READ_FAKE_HTTP: {
        int fakeHttpHeadStartIndex = in.readerIndex();

        int fakeHttpHeadEndIndex = in.forEachByte(new ByteBufProcessor() {
            int c = 0;

            @Override// w  w w  .  j  av a 2s  . c  o m
            public boolean process(byte value) throws Exception {

                if (value == '\r' || value == '\n') {
                    c++;
                } else {
                    c = 0;
                }

                //logger.info("value=" + value + ", c=" + c);

                if (c >= 4) {
                    return false;
                } else {
                    return true;
                }
            }
        });

        logger.debug("s: " + fakeHttpHeadStartIndex);
        logger.debug("e: " + fakeHttpHeadEndIndex);

        if (fakeHttpHeadEndIndex == -1) {
            logger.warn("w: " + fakeHttpHeadStartIndex);
            break;
        }

        byte[] buf = new byte[fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1];
        in.readBytes(buf, 0, fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1);
        String s = TextUtil.fromUTF8Bytes(buf);

        //logger.info(s);

        String[] ss = StringUtils.split(s, "\r\n");

        //System.out.println(s + "" + this + " " + Thread.currentThread().getName());

        for (String line : ss) {
            if (StringUtils.startsWith(line, "X-C:")) {
                String lenStr = StringUtils.trim(StringUtils.split(line, ":")[1]);
                //System.out.println(lenStr + "" + this + " " + Thread.currentThread().getName());
                //System.out.println("*****************************************");
                try {
                    length = Integer.parseInt(lenStr, 16);
                    trafficLogger.info("D," + LocalConfig.ins().getUser() + "," + length);
                } catch (Throwable t) {
                    logger.error("--------------------------------------");
                    logger.error(s + "" + this + " " + Thread.currentThread().getName());
                    logger.error("--------------------------------------");
                }

            }
        }

        this.checkpoint(STATE.READ_CONTENT);
    }
    case READ_CONTENT: {
        if (length > 0) {
            byte[] buf = new byte[length];
            in.readBytes(buf, 0, length);

            byte[] res = new byte[length];

            for (int i = 0; i < length; i++) {
                res[i] = (byte) (buf[i] ^ (LocalConfig.ins().getEncryptKey() & 0xFF));
            }

            ByteBuf outBuf = ctx.alloc().buffer();

            outBuf.writeBytes(res);

            out.add(outBuf);
        }

        this.checkpoint(STATE.READ_FAKE_HTTP);
        break;
    }
    default:
        throw new Error("Shouldn't reach here.");
    }

}

From source file:com.xx_dev.apn.socks.remote.FakeHttpServerDecoder.java

protected void _decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (this.state()) {
    case READ_FAKE_HTTP: {
        int fakeHttpHeadStartIndex = in.readerIndex();

        int fakeHttpHeadEndIndex = in.forEachByte(new ByteBufProcessor() {
            int c = 0;

            @Override/*from   w w  w  .  j av a 2 s .c  o m*/
            public boolean process(byte value) throws Exception {

                if (value == '\r' || value == '\n') {
                    c++;
                } else {
                    c = 0;
                }

                //logger.info("value=" + value + ", c=" + c);

                if (c >= 4) {
                    return false;
                } else {
                    return true;
                }
            }
        });

        logger.debug("s: " + fakeHttpHeadStartIndex);
        logger.debug("e: " + fakeHttpHeadEndIndex);

        if (fakeHttpHeadEndIndex == -1) {
            logger.warn("w: " + fakeHttpHeadStartIndex);
            break;
        }

        byte[] buf = new byte[fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1];
        in.readBytes(buf, 0, fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1);
        String s = TextUtil.fromUTF8Bytes(buf);

        //logger.info(s);

        String[] ss = StringUtils.split(s, "\r\n");

        //System.out.println(s + "" + this + " " + Thread.currentThread().getName());

        for (String line : ss) {
            if (StringUtils.startsWith(line, "X-C:")) {
                String lenStr = StringUtils.trim(StringUtils.split(line, ":")[1]);
                //System.out.println(lenStr + "" + this + " " + Thread.currentThread().getName());
                //System.out.println("*****************************************");
                try {
                    length = Integer.parseInt(lenStr, 16);
                } catch (Throwable t) {
                    logger.error("--------------------------------------");
                    logger.error(s + "" + this + " " + Thread.currentThread().getName());
                    logger.error("--------------------------------------");
                }

            }

            if (StringUtils.startsWith(line, "X-U:")) {
                String user = StringUtils.trim(StringUtils.split(line, ":")[1]);
                ctx.channel().attr(NettyAttributeKey.LINK_USER).set(user);
                logger.info(user);
            }
        }

        this.checkpoint(STATE.READ_CONTENT);
    }
    case READ_CONTENT: {

        trafficLogger.info("U," + ctx.channel().attr(NettyAttributeKey.LINK_USER).get() + "," + length);

        if (length > 0) {

            byte[] buf = new byte[length];
            in.readBytes(buf, 0, length);

            byte[] res = new byte[length];

            for (int i = 0; i < length; i++) {
                res[i] = (byte) (buf[i] ^ (RemoteConfig.ins().getEncryptKey() & 0xFF));
            }

            ByteBuf outBuf = ctx.alloc().buffer();

            outBuf.writeBytes(res);

            out.add(outBuf);
        }

        this.checkpoint(STATE.READ_FAKE_HTTP);
        break;
    }
    default:
        throw new Error("Shouldn't reach here.");
    }

}