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

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

Introduction

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

Prototype

public static String substring(String str, int start) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

Usage

From source file:jenkins.plugins.tanaguru.ProjectTanaguruAction.java

private String buildAuditResultUrl(String line, String webappUrl) {
    String auditId = StringUtils.substring(line, StringUtils.indexOf(line, ":") + 1).trim();
    if (StringUtils.endsWith(webappUrl, "/")) {
        return webappUrl + URL_PREFIX_RESULT + auditId;
    } else {/*  www.j a v  a2 s  . c o  m*/
        return webappUrl + "/" + URL_PREFIX_RESULT + auditId;
    }
}

From source file:controllers.modules.cas.SecureCAS.java

public static void handleLogout(String body) throws Throwable {
    int i = StringUtils.indexOf(body, LOGOUT_REQ_PARAMETER);
    String postBody = URLDecoder.decode(body, "UTF-8");
    if (i == 0) {
        String logoutRequestMessage = StringUtils.substring(postBody, LOGOUT_REQ_PARAMETER.length() + 1);
        if (StringUtils.isNotEmpty(logoutRequestMessage)) {

            Document document = XML.getDocument(logoutRequestMessage);
            if (document != null) {
                NodeList nodeList = document.getElementsByTagName("samlp:SessionIndex");
                if (nodeList != null && nodeList.getLength() > 0) {
                    Node node = nodeList.item(0);
                    String ticket = node.getTextContent();
                    String stKey = ST + "_" + ticket;
                    String username = Cache.get(stKey, String.class);
                    if (username != null) {
                        Cache.delete(stKey);
                        Cache.set(LOGOUT_TAG + "_" + username, 1, TEN_YEARS_EXPIRATION);
                        Logger.debug("Mark that %s has been logout ", username);
                        return;
                    }/*from   ww  w  .  j  a va  2s.c om*/
                }
            }
        }
    }
    Logger.warn("illegal logout message: %s", postBody);
}

From source file:com.intel.cosbench.exporter.ScriptsLogExporter.java

private void exportScriptLog(Writer writer, String logCtx, String driver) throws IOException {
    int idx = StringUtils.indexOf(logCtx, ";");
    if (idx < 0 || idx + 1 == logCtx.length())
        return;//from w  ww. j  a  v  a 2s.c  o  m
    String scriptName = StringUtils.left(logCtx, idx);
    String log = StringUtils.substring(logCtx, idx + 1);
    writer.write("-----------------");
    writer.write("-----------------");
    writer.write(" driver: " + driver + "  script: " + scriptName + ' ');
    writer.write("-----------------");
    writer.write("-----------------");
    writer.write('\n');
    writer.write(log);
}

From source file:co.marcin.novaguilds.command.admin.guild.CommandAdminGuildResetPoints.java

@Override
public void execute(CommandSender sender, String[] args) throws Exception {
    if (args.length == 0) {
        getCommand().getUsageMessage().send(sender);
        return;//w ww.  j a v a  2 s .c  om
    }

    String condition = args[0];
    ConditionType conditionType = null;

    if (condition.equalsIgnoreCase("all")) {
        conditionType = ConditionType.ALL;
    } else {
        switch (condition.charAt(0)) {
        case '<':
            conditionType = ConditionType.SMALLER;
            break;
        case '>':
            conditionType = ConditionType.LARGER;
            break;
        case '=':
            conditionType = ConditionType.EQUAL;
            break;
        }
    }

    if (conditionType == null) {
        Message.CHAT_ADMIN_GUILD_RESET_POINTS_INVALIDCONDITIONTYPE.send(sender);
        return;
    }

    Map<VarKey, String> vars = new HashMap<>();
    vars.put(VarKey.CHAR, String.valueOf(condition.charAt(0)));

    if (condition.length() == 1) {
        Message.CHAT_ADMIN_GUILD_RESET_POINTS_NOVALUE.vars(vars).send(sender);
        return;
    }

    int value = 0;
    if (conditionType != ConditionType.ALL) {
        String valueString = StringUtils.substring(condition, 1);

        if (!NumberUtils.isNumeric(valueString)) {
            Message.CHAT_ENTERINTEGER.send(sender);
            return;
        }

        value = Integer.valueOf(valueString);
    }

    int count = 0;
    for (NovaGuild guild : plugin.getGuildManager().getGuilds()) {
        int points = guild.getPoints();
        boolean passed = conditionType == ConditionType.ALL;

        switch (conditionType) {
        case SMALLER:
            passed = points < value;
            break;
        case LARGER:
            passed = points > value;
            break;
        case EQUAL:
            passed = points == value;
            break;
        }

        if (passed) {
            int newPoints;

            if (args.length == 2) {
                String newPointsString = args[1];

                if (!NumberUtils.isNumeric(newPointsString)) {
                    Message.CHAT_ENTERINTEGER.send(sender);
                    return;
                }

                newPoints = Integer.valueOf(newPointsString);

                if (newPoints < 0) {
                    Message.CHAT_BASIC_NEGATIVENUMBER.send(sender);
                    return;
                }
            } else {
                newPoints = Config.GUILD_START_POINTS.getInt();
            }

            guild.setPoints(newPoints);
            TabUtils.refresh(guild);

            count++;
        }
    }
    vars.put(VarKey.COUNT, String.valueOf(count));

    Message.CHAT_ADMIN_GUILD_RESET_POINTS_SUCCESS.vars(vars).send(sender);
}

From source file:gov.nih.nci.cacis.ip.mirthconnect.CanonicalModelProcessor.java

/**
 * Method accepts canonical data for processing
 * //from w  ww. jav  a 2 s. co  m
 * @param request CaCISRequest
 * @return response CaCISResponse
 * @throws AcceptCanonicalFault Fault
 * @throws
 */
@WebResult(name = "caCISResponse", targetNamespace = CACIS_NS, partName = "parameter")
@WebMethod
public gov.nih.nci.cacis.CaCISResponse acceptCanonical(
        @WebParam(partName = "parameter", name = "caCISRequest", targetNamespace = CACIS_NS) CaCISRequest request)
        throws AcceptCanonicalFault {

    final CaCISResponse response = new CaCISResponse();

    final StringWriter sw = new StringWriter();
    try {
        final JAXBContext jc = JAXBContext.newInstance(CaCISRequest.class);
        final Marshaller m = jc.createMarshaller();

        final PrintWriter pw = new PrintWriter(sw);
        m.marshal(request, pw);
        response.setStatus(ResponseStatusType.SUCCESS);
    } catch (JAXBException jaxE) {
        throw new AcceptCanonicalFault("Error Marshalling object", jaxE);
    }

    try {
        String mcResponse = webServiceMessageReceiver.processData(sw.toString());

        if (mcResponse != null && (mcResponse.indexOf("Error") > -1 || mcResponse.indexOf("Exception") > -1
                || mcResponse.indexOf("ERROR") > -1 || mcResponse.indexOf("error") > -1)) {
            mcResponse = StringUtils.remove(mcResponse, "SUCCESS:");
            String channelUid = StringUtils.substringBetween(mcResponse, "(", ")");
            if (channelUid != null) {
                mcResponse = StringUtils.remove(mcResponse, "(" + channelUid + ")");
            }
            throw new AcceptCanonicalFault(
                    StringUtils.substring(mcResponse, StringUtils.lastIndexOf(mcResponse, ':')));
        }
        response.setStatus(ResponseStatusType.SUCCESS);
        return response;
        // CHECKSTYLE:OFF
    } catch (Exception e) {
        // CHECKSTYLE:ON
        //throw new AcceptCanonicalFault("Error processing message!" + e.getMessage(), e);
        throw new AcceptCanonicalFault(e.getMessage(), e);
    }
}

From source file:com.vmware.bdd.usermgmt.SssdConfigurationGenerator.java

protected void load() {
    if (isTemplateContentEmpty()) {
        Map<UserMgmtServer.Type, StringBuilder> templateMap = new HashMap<>();
        synchronized (templateContent) {
            for (UserMgmtServer.Type type : UserMgmtServer.Type.values()) {
                File templateFile = CommonUtil.getConfigurationFile(
                        "usermgmt" + File.separator + SSSD_CONF_TEMPLATES + type, "sssd.conf");
                HashMap<String, String> typeMap = new HashMap<>();

                StringBuilder stringBuilder = new StringBuilder();
                try (BufferedReader templateBufReader = new BufferedReader(new FileReader(templateFile))) {
                    String line = templateBufReader.readLine();

                    boolean flag = false;
                    while (line != null) {
                        if (StringUtils.isNotBlank(line)) {
                            if (!flag) {
                                flag = StringUtils.equals(line, "[domain/LDAP]");
                            }/* w ww.  ja  va2  s . c om*/

                            if (flag) {
                                int keyValueSepIndex = line.indexOf('=');
                                if (keyValueSepIndex != -1) {
                                    typeMap.put(line.substring(0, keyValueSepIndex).trim(),
                                            StringUtils.substring(line, keyValueSepIndex + 1).trim());
                                }
                            }
                        }
                        stringBuilder.append(line).append('\n');
                        line = templateBufReader.readLine();
                    }
                } catch (FileNotFoundException fnf) {
                    throw new UserMgmtException("SSSD_CONF_TEMPLATE_NOT_FOUND", fnf,
                            templateFile.getAbsolutePath());
                } catch (IOException ioe) {
                    throw new UserMgmtException("SSSD_CONF_TEMPLATE_READ_ERR", ioe,
                            templateFile.getAbsolutePath());
                }
                templateMap.put(type, stringBuilder);

                mapping.put(type, typeMap);
            }

            templateContent.putAll(templateMap);

        }
    }
}

From source file:de.hybris.platform.acceleratorservices.process.strategies.impl.DefaultEmailTemplateTranslationStrategy.java

protected List<String> getPropertiesRootPath(final RendererTemplateModel renderTemplate,
        final String languageIso) {
    final MediaModel content = renderTemplate.getContent();
    final List<String> messageSources = new ArrayList<String>();
    if (content != null) {
        BufferedReader reader = null;
        try {/*from w  w  w  .  j  ava  2 s .com*/
            reader = new BufferedReader(
                    new InputStreamReader(mediaService.getStreamFromMedia(content), "UTF-8"));
            String line = reader.readLine();
            while (StringUtils.isNotEmpty(line)) {
                String messageSource = null;

                if (line.trim().startsWith("<")) {
                    break;
                } else if (line.contains("## messageSource=")) {
                    messageSource = StringUtils.substring(line, line.indexOf("## messageSource=") + 17);
                } else if (line.contains("##messageSource=")) {
                    messageSource = StringUtils.substring(line, line.indexOf("##messageSource=") + 16);
                }

                if (StringUtils.isNotEmpty(messageSource)) {
                    if (messageSource.contains("$lang")) {
                        messageSource = messageSource.replace("$lang", languageIso);
                    }
                    messageSources.add(messageSource);
                }
                line = reader.readLine();
            }
            return messageSources;
        } catch (final IOException e) {
            throw new RendererException("Problem during rendering", e);
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }
    return messageSources;
}

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  .  ja v a 2s .c  om*/
    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:gate.corpora.twitter.Population.java

private static Document newDocument(URL url, int counter, int digits) throws ResourceInstantiationException {
    Document document = Factory.newDocument("");
    String code = StringUtils.leftPad(Integer.toString(counter), digits, '0');
    String name = StringUtils.stripToEmpty(StringUtils.substring(url.getPath(), 1)) + "_" + code;
    document.setName(name);/*from   w  ww. java2 s .  co m*/
    document.setSourceUrl(url);
    document.getFeatures().put(Document.DOCUMENT_MIME_TYPE_PARAMETER_NAME, TweetUtils.MIME_TYPE);
    document.getFeatures().put("gate.SourceURL", url.toString());
    return document;
}

From source file:it.openutils.mgnlaws.magnolia.AmazonMgnlServletContextListener.java

protected void initEc2(String accessKey, String secretKey, String endpoint)
        throws IOException, AmazonEc2InstanceNotFound {
    String ec2InstanceId;/*from  ww  w.j  a va  2s .  c om*/
    BufferedReader in = null;
    try {
        URL url = new URL("http://169.254.169.254/latest/meta-data/instance-id");
        URLConnection connection = url.openConnection();
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        ec2InstanceId = in.readLine();
        in.close();
    } finally {
        IOUtils.closeQuietly(in);
    }

    AmazonEC2Client client = new AmazonEC2Client(new BasicAWSCredentials(accessKey, secretKey));
    client.setEndpoint(endpoint);
    DescribeInstancesResult result = client
            .describeInstances(new DescribeInstancesRequest().withInstanceIds(ec2InstanceId));
    if (result.getReservations().size() > 0 && result.getReservations().get(0).getInstances().size() > 0) {
        ec2Instance = result.getReservations().get(0).getInstances().get(0);
        if (ec2Instance == null) {
            // should never happen
            throw new AmazonEc2InstanceNotFound(ec2InstanceId);
        }
    } else {
        throw new AmazonEc2InstanceNotFound(ec2InstanceId);
    }

    for (Tag tag : ec2Instance.getTags()) {
        if (StringUtils.startsWith(tag.getKey(), "__")) {
            System.setProperty(StringUtils.substring(tag.getKey(), 2), tag.getValue());
        } else {
            System.setProperty("aws.instance." + tag.getKey(), tag.getValue());
        }
    }

    String clusterId = System.getProperty(EC2_TAG_CLUSTERID);
    if (StringUtils.isNotEmpty(clusterId)) {
        System.setProperty(JR_CLUSTERID, clusterId);
    }
}