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

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

Introduction

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

Prototype

public static String replace(String text, String searchString, String replacement) 

Source Link

Document

Replaces all occurrences of a String within another String.

Usage

From source file:com.google.gdt.eclipse.designer.model.property.DateTimeFormatPropertyEditor.java

private String getSourceByTemplate(String source) {
    return (StringUtils.isEmpty(m_sourceTemplate) ? source
            : StringUtils.replace(m_sourceTemplate, "%value%", source)).trim();
}

From source file:com.iw.plugins.spindle.core.util.JarEntryFileUtil.java

public static String getPackageName(IJarEntryResource entry) {
    String content = entry.toString();
    int start = content.indexOf("::");
    content = content.substring(start + 2, content.length() - 1);
    int nameLength = entry.getName().length();
    if (content.length() == nameLength)
        return "";
    int stop = content.lastIndexOf('/');
    return StringUtils.replace(content.substring(0, stop), "/", ".");
}

From source file:info.magnolia.importexport.BootstrapUtil.java

/**
 * I.e. given a resource path like <code>/mgnl-bootstrap/foo/config.server.i18n.xml</code> it will return <code>/server</code>.
 *///from  ww  w .  ja  v  a 2  s  . c  om
public static String getPathnameFromResource(final String resourcePath) {
    String resourceName = StringUtils.replace(resourcePath, "\\", "/");

    String name = getFilenameFromResource(resourceName, ".xml");
    String fullPath = DataTransporter.revertExportPath(name);
    String pathName = StringUtils.substringAfter(StringUtils.substringBeforeLast(fullPath, "/"), "/");

    if (!pathName.startsWith("/")) {
        pathName = "/" + pathName;
    }
    return pathName;
}

From source file:eionet.cr.util.sesame.SPARQLQueryUtil.java

/**
 * Changes SPARQL query to use IRI function for this parameter value. ?subject -> IRI(?subject)
 *
 * @param query SPARQL query// w  w  w .  j  a va  2s .c  o  m
 * @param paramName parameter to be replaced
 * @return
 */
public static String parseIRIQuery(String query, String paramName) {
    String tmpQuery = query;
    tmpQuery = StringUtils.replace(tmpQuery, "?" + paramName, "IRI(?" + paramName + ")");

    return tmpQuery;
}

From source file:com.cws.esolutions.security.processors.impl.CertificateRequestProcessorImpl.java

public CertificateResponse listActiveRequests(final CertificateRequest request)
        throws CertificateRequestException {
    final String methodName = ICertificateRequestProcessor.CNAME
            + "#listActiveRequests(final CertificateRequest request) throws CertificateRequestException";

    if (DEBUG) {//from  www  .  j av  a2s  . c  om
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("CertificateRequest: {}", request);
    }

    CertificateResponse response = new CertificateResponse();
    ArrayList<String> availableRequests = new ArrayList<String>();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount authUser = request.getUserAccount();
    final File rootDirectory = FileUtils.getFile(certConfig.getRootDirectory());
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory());
    final File certificateDirectory = FileUtils.getFile(certConfig.getStoreDirectory());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("authUser: {}", authUser);
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("certificateDirectory: {}", certificateDirectory);
    }

    try {
        if (!(rootDirectory.canWrite())) {
            if (!(rootDirectory.mkdirs())) {
                throw new IOException(
                        "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
            }
        }

        if (!(csrDirectory.canWrite())) {
            if (!(csrDirectory.mkdirs())) {
                throw new IOException(
                        "Private directory either does not exist or cannot be written to. Cannot continue.");
            }
        }

        if (!(certificateDirectory.canWrite())) {
            if (!(certificateDirectory.mkdirs())) {
                throw new IOException(
                        "Private directory either does not exist or cannot be written to. Cannot continue.");
            }
        }

        for (File csrFile : FileUtils.listFiles(csrDirectory,
                new String[] { SecurityServiceConstants.CSR_FILE_EXT.replace(".", "") }, true)) {
            if (DEBUG) {
                DEBUGGER.debug("File: {}", csrFile);
            }

            String csrFileName = csrFile.getName();

            if (DEBUG) {
                DEBUGGER.debug("csrFileName: {}", csrFileName);
            }

            for (File certFile : FileUtils.listFiles(certificateDirectory,
                    new String[] { SecurityServiceConstants.CERTIFICATE_FILE_EXT.replace(".", "") }, true)) {
                if (DEBUG) {
                    DEBUGGER.debug("File: {}", certFile);
                }

                String certFileName = certFile.getName();

                if (DEBUG) {
                    DEBUGGER.debug("certFileName: {}", certFileName);
                }

                if (!(StringUtils.equals(
                        StringUtils.replace(csrFileName, SecurityServiceConstants.CSR_FILE_EXT, ""), StringUtils
                                .replace(certFileName, SecurityServiceConstants.CERTIFICATE_FILE_EXT, "")))) {
                    availableRequests.add(csrFile.toString());

                    if (DEBUG) {
                        DEBUGGER.debug("availableRequests: {}", availableRequests);
                    }
                }
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("availableRequests: {}", availableRequests);
        }

        response.setRequestStatus(SecurityRequestStatus.SUCCESS);
        response.setAvailableRequests(availableRequests);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new CertificateRequestException(iox.getMessage(), iox);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.LISTCSR);
            auditEntry.setUserAccount(authUser);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getApplicationName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:gov.va.med.pharmacy.peps.presentation.common.displaytag.DefaultHssfExportView.java

/**
 * escapeColumnValue//from  w  w  w  .j  av a 2  s .co m
 * @param rawValue unmodified text
 * @return String with html/xml removed
 */
protected String escapeColumnValue(Object rawValue) {

    if (rawValue == null) {
        return null;
    }

    String returnString = ObjectUtils.toString(rawValue);

    // Extract text
    try {
        returnString = extractText(returnString);
    } catch (IOException e) {
        LOG.warn(e.getLocalizedMessage());
    }

    // escape the String to get the tabs, returns, newline explicit as \t \r \n
    returnString = StringEscapeUtils.escapeJava(StringUtils.trimToEmpty(returnString));

    // remove tabs, insert four whitespaces instead
    returnString = StringUtils.replace(StringUtils.trim(returnString), "\\t", "    ");

    // remove the return, only newline valid in excel
    returnString = StringUtils.replace(StringUtils.trim(returnString), "\\r", " ");

    // unescape so that \n gets back to newline
    returnString = StringEscapeUtils.unescapeJava(returnString);

    return returnString;
}

From source file:gsn.storage.SQLUtils.java

public static StringBuilder newRewrite(CharSequence query, CharSequence tableNameToRename,
        CharSequence replaceTo) {
    // Selecting strings between pair of "" : (\"[^\"]*\")
    // Selecting tableID.tableName or tableID.* : (\\w+(\\.(\w+)|\\*))
    // The combined pattern is : (\"[^\"]*\")|(\\w+\\.((\\w+)|\\*))
    Matcher matcher = pattern.matcher(query);
    StringBuffer result = new StringBuffer();
    while (matcher.find()) {
        if (matcher.group(2) == null)
            continue;
        String tableName = matcher.group(3);
        if (tableName.equals(tableNameToRename)) {
            // $4 means that the 4th group of the match should be appended to the
            // string (the forth group contains the field name).
            if (replaceTo != null)
                matcher.appendReplacement(result, new StringBuilder(replaceTo).append("$4").toString());
        }//from   ww w .j  a va 2  s  .  co  m
    }
    String toReturn = matcher.appendTail(result).toString().toLowerCase();
    int indexOfFrom = toReturn.indexOf(" from ") >= 0 ? toReturn.indexOf(" from ") + " from ".length() : 0;
    int indexOfWhere = (toReturn.lastIndexOf(" where ") > 0 ? (toReturn.lastIndexOf(" where "))
            : toReturn.length());
    String selection = toReturn.substring(indexOfFrom, indexOfWhere);
    Pattern fromClausePattern = Pattern.compile("\\s*(\\w+)\\s*", Pattern.CASE_INSENSITIVE);
    Matcher fromClauseMather = fromClausePattern.matcher(selection);
    result = new StringBuffer();
    while (fromClauseMather.find()) {
        if (fromClauseMather.group(1) == null)
            continue;
        String tableName = fromClauseMather.group(1);
        if (tableName.equals(tableNameToRename) && replaceTo != null)
            fromClauseMather.appendReplacement(result, replaceTo.toString() + " ");
    }
    String cleanFromClause = fromClauseMather.appendTail(result).toString();
    String finalResult = StringUtils.replace(toReturn, selection, cleanFromClause);
    return new StringBuilder(finalResult);
}

From source file:com.haulmont.cuba.web.sys.CubaVaadinServletService.java

public CubaVaadinServletService(VaadinServlet servlet, DeploymentConfiguration deploymentConfiguration)
        throws ServiceException {
    super(servlet, deploymentConfiguration);

    Configuration configuration = AppBeans.get(Configuration.NAME);
    webConfig = configuration.getConfig(WebConfig.class);
    webAuthConfig = configuration.getConfig(WebAuthConfig.class);
    testMode = configuration.getConfig(GlobalConfig.class).getTestMode();

    ServletContext sc = servlet.getServletContext();
    String resourcesTimestamp = sc.getInitParameter("webResourcesTs");
    if (StringUtils.isNotEmpty(resourcesTimestamp)) {
        this.webResourceTimestamp = resourcesTimestamp;
    } else {/*from   ww w  .  j av a2s  .co  m*/
        this.webResourceTimestamp = "DEBUG";
    }

    addSessionInitListener(event -> {
        WrappedSession wrappedSession = event.getSession().getSession();
        wrappedSession.setMaxInactiveInterval(webConfig.getHttpSessionExpirationTimeoutSec());

        HttpSession httpSession = wrappedSession instanceof WrappedHttpSession
                ? ((WrappedHttpSession) wrappedSession).getHttpSession()
                : null;

        log.debug("HttpSession {} initialized, timeout={}sec", httpSession,
                wrappedSession.getMaxInactiveInterval());
    });

    addSessionDestroyListener(event -> {
        WrappedSession wrappedSession = event.getSession().getSession();
        HttpSession httpSession = wrappedSession instanceof WrappedHttpSession
                ? ((WrappedHttpSession) wrappedSession).getHttpSession()
                : null;

        log.debug("HttpSession destroyed: {}", httpSession);
        App app = event.getSession().getAttribute(App.class);
        if (app != null) {
            app.cleanupBackgroundTasks();
        }
    });

    setSystemMessagesProvider(systemMessagesInfo -> {
        Locale locale = systemMessagesInfo.getLocale();

        CustomizedSystemMessages msgs = new CustomizedSystemMessages();

        if (AppContext.isStarted()) {
            try {
                Messages messages = AppBeans.get(Messages.NAME);

                msgs.setInternalErrorCaption(messages.getMainMessage("internalErrorCaption", locale));
                msgs.setInternalErrorMessage(messages.getMainMessage("internalErrorMessage", locale));

                msgs.setCommunicationErrorCaption(messages.getMainMessage("communicationErrorCaption", locale));
                msgs.setCommunicationErrorMessage(messages.getMainMessage("communicationErrorMessage", locale));

                msgs.setSessionExpiredCaption(messages.getMainMessage("sessionExpiredErrorCaption", locale));
                msgs.setSessionExpiredMessage(messages.getMainMessage("sessionExpiredErrorMessage", locale));
            } catch (Exception e) {
                log.error("Unable to set system messages", e);
                throw new RuntimeException("Unable to set system messages. "
                        + "It usually happens when the middleware web application is not responding due to "
                        + "errors on start. See logs for details.", e);
            }
        }

        String redirectUri;
        if (RequestContext.get() != null) {
            HttpServletRequest request = RequestContext.get().getRequest();
            redirectUri = StringUtils.replace(request.getRequestURI(), "/UIDL", "");
        } else {
            String webContext = AppContext.getProperty("cuba.webContextName");
            redirectUri = "/" + webContext;
        }

        msgs.setInternalErrorURL(redirectUri + "?restartApp");

        return msgs;
    });
}

From source file:io.lightlink.excel.SheetTemplateHandler.java

private String protectSpecialCharacters(String originalUnprotectedString) {
    if (originalUnprotectedString == null) {
        return null;
    }/*from   w  w w. j  a  va  2 s  .  c o m*/
    boolean anyCharactersProtected = false;

    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < originalUnprotectedString.length(); i++) {
        char ch = originalUnprotectedString.charAt(i);

        boolean controlCharacter = ch < 32;

        if (controlCharacter) {
            if (ch == '\n' || ch == '\r')
                stringBuffer.append(ch);
            else if (ch == '\t')
                stringBuffer.append(" ");

            anyCharactersProtected = true;
        } else {
            stringBuffer.append(ch);
        }
    }
    String res = anyCharactersProtected ? stringBuffer.toString() : originalUnprotectedString;

    if (res.contains("]]>")) {
        res = StringUtils.replace(originalUnprotectedString, "]]>", "]]]]><![CDATA[>");
    }

    return res;
}

From source file:gov.nih.nci.cabig.caaers.domain.repository.ReportVersionRepository.java

/**
 * Will send a fake AdEERS failure message so that the post process like E2B ack etc will be sent out successfully.
 * @param reportVersion/*from   www.  jav  a 2 s.  c om*/
 */
private void sendFailureXMLMessage(ReportVersion reportVersion) {

    if (responseMessageProcessor == null)
        return;

    String responseXMLTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
            + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Body>"
            + "<submitAEDataXMLAsAttachmentResponse xmlns=\"http://types.ws.adeers.ctep.nci.nih.gov\">"
            + "<ns1:AEReportJobInfo xmlns:ns1=\"http://localhost:8080/AdEERSWSMap/services/AEReportXMLService\"><jobID xsi:type=\"xsd:string\" xmlns=\"\">0000</jobID>"
            + "<patientID xsi:type=\"xsd:string\" xmlns=\"\">${subjectId}</patientID><protocolNumber xsi:type=\"xsd:string\" xmlns=\"\">${protocolId}</protocolNumber>"
            + "<jobExceptions xmlns=\"\"><code>Error</code><description>Report is stuck at submission, so forcefully marking it as failed</description>"
            + "</jobExceptions><reportStatus xsi:nil=\"true\" xmlns=\"\"/><comments xsi:type=\"xsd:string\" xmlns=\"\">Report is stuck at submission, so forcefully marking it as failed</comments>"
            + "<CAEERS_AEREPORT_ID>${aeReportId}</CAEERS_AEREPORT_ID><CAAERSRID>${reportId}</CAAERSRID><SUBMITTER_EMAIL>${submitterEmail}</SUBMITTER_EMAIL><MESSAGE_COMBO_ID>${messageComboId}</MESSAGE_COMBO_ID>"
            + "</ns1:AEReportJobInfo></submitAEDataXMLAsAttachmentResponse>"
            + "</soapenv:Body></soapenv:Envelope>";
    Report report = reportVersion.getReport();
    String createdDateAndTime = DateUtils.formatDate(report.getAeReport().getCreatedAt(), "yyyyMMddHHmmss");
    Map<String, String> replacementMap = new HashMap<String, String>();
    String submiterEmail = "caaers@semanticbits.com";
    if (report.getSubmitter() != null) {
        submiterEmail = report.getSubmitter().getEmailAddress();
    }

    replacementMap.put("${reportId}", "" + report.getId());
    replacementMap.put("${aeReportId}", "" + report.getAeReport().getId());
    replacementMap.put("${protocolId}", report.getAeReport().getStudy().getPrimaryIdentifierValue());
    replacementMap.put("${subjectId}", report.getAeReport().getParticipant().getPrimaryIdentifierValue());
    replacementMap.put("${messageComboId}", report.getCaseNumber() + "::" + createdDateAndTime);
    replacementMap.put("${submitterEmail}", submiterEmail);

    if (StringUtils.isBlank(replacementMap.get("${reportId}"))) {
        log.error("The Report ID for the stuck report is null! ReportVersionId: " + reportVersion.getId());
    }

    if (StringUtils.isBlank(replacementMap.get("${aeReportId}"))) {
        log.error("The AE Report ID for the stuck report is null! ReportVersionId: " + reportVersion.getId());
    }

    String xmlMessage = responseXMLTemplate;
    for (Map.Entry<String, String> entry : replacementMap.entrySet()) {
        xmlMessage = StringUtils.replace(xmlMessage, entry.getKey(), entry.getValue());
    }
    responseMessageProcessor.processMessage(xmlMessage);
}