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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.soolr.core.web.Servlets.java

public static String getHost(HttpServletRequest request) {
    String requestURL = request.getRequestURL().toString();
    String requestURI = request.getRequestURI();
    String host = StringUtils.substringBefore(requestURL, requestURI);
    return host;//from ww  w  . j  a  v  a  2s.c  o m
}

From source file:com.xpn.xwiki.plugin.watchlist.WatchListJob.java

/**
 * Method called from the scheduler./* w w  w.j ava2s  .  c  om*/
 * 
 * @param jobContext Context of the request
 * @throws JobExecutionException if the job execution fails.
 */
@Override
public void executeJob(JobExecutionContext jobContext) throws JobExecutionException {
    try {
        init(jobContext);

        if (this.watchListJobObject == null) {
            return;
        }

        List<String> subscribers = getSubscribers();
        Date previousFireTime = getPreviousFireTime();
        WatchListEventMatcher eventMatcher = new WatchListEventMatcher(previousFireTime, this.context);
        setPreviousFireTime();

        if (!hasSubscribers()) {
            return;
        }

        if (eventMatcher.getEventNumber() == 0) {
            return;
        }

        for (String subscriber : subscribers) {
            try {
                List<String> wikis = this.plugin.getStore().getWatchedElements(subscriber, ElementType.WIKI,
                        this.context);
                List<String> spaces = this.plugin.getStore().getWatchedElements(subscriber, ElementType.SPACE,
                        this.context);
                List<String> documents = this.plugin.getStore().getWatchedElements(subscriber,
                        ElementType.DOCUMENT, this.context);
                List<String> users = this.plugin.getStore().getWatchedElements(subscriber, ElementType.USER,
                        this.context);
                List<WatchListEvent> matchingEvents = eventMatcher.getMatchingEvents(wikis, spaces, documents,
                        users, subscriber, this.context);
                String userWiki = StringUtils.substringBefore(subscriber, WatchListStore.WIKI_SPACE_SEP);

                // If events have occurred on at least one element watched by the user, send the email
                if (matchingEvents.size() > 0) {
                    this.plugin.getNotifier().sendEmailNotification(subscriber, matchingEvents,
                            getEmailTemplate(userWiki), previousFireTime, this.context);
                }
            } catch (Exception e) {
                LOGGER.error("Failed to send watchlist notification to user [{}]", subscriber, e);
            }
        }
    } catch (Exception e) {
        // We're in a job, we don't throw exceptions
        LOGGER.error("Exception while running job", e);
    } finally {
        this.context.getWiki().getStore().cleanUp(this.context);
        cleanupComponents();
    }
}

From source file:com.alibaba.rocketmq.filtersrv.filter.DynaCode.java

public static String getPackageName(String code) {
    String packageName = StringUtils.substringBefore(StringUtils.substringAfter(code, "package "), ";").trim();
    return packageName;
}

From source file:in.mycp.workers.IpAddressWorker.java

@Async
public void associateAddress(final Infra infra, final AddressInfoP addressInfoP) {
    try {//from ww  w. j  a  va  2 s. c om
        Jec2 ec2 = getNewJce2(infra);

        try {
            logger.info("associateAddress address " + addressInfoP.getPublicIp() + " to instance "
                    + addressInfoP.getInstanceId());
            ec2.associateAddress(addressInfoP.getInstanceId(), addressInfoP.getPublicIp());
        } catch (Exception e) {
            logger.error(e);//e.printStackTrace();
            if (e.getMessage().indexOf("Permission denied while") > -1) {
                throw new Exception("Permission denied.");
            } else if (e.getMessage().indexOf("Number of retries exceeded") > -1) {
                throw new Exception("No Connectivity to Cloud");
            }
        }
        String instanceIdOrig = addressInfoP.getInstanceId();
        if (StringUtils.contains(instanceIdOrig, " ")) {
            instanceIdOrig = StringUtils.substringBefore(instanceIdOrig, " ");
        }

        InstanceP orig_compute = null;
        try {
            orig_compute = InstanceP.findInstancePsByInstanceIdEquals(instanceIdOrig).getSingleResult();
        } catch (Exception e) {
            logger.error(e);//e.printStackTrace();
        }

        AddressInfoP addressInfoP4PublicIp = null;
        try {
            addressInfoP4PublicIp = AddressInfoP.findAddressInfoPsByPublicIpEquals(addressInfoP.getPublicIp())
                    .getSingleResult();
        } catch (Exception e) {
            logger.error(e);//e.printStackTrace();
        }

        AddressInfoP addressInfoP4InstanceId = null;
        try {
            addressInfoP4InstanceId = AddressInfoP.findAddressInfoPsByInstanceIdLike(instanceIdOrig)
                    .getSingleResult();
        } catch (Exception e) {
            logger.error(e);//e.printStackTrace();
        }

        boolean match = false;
        int START_SLEEP_TIME = 5000;
        int waitformaxcap = START_SLEEP_TIME * 10;
        long now = 0;
        outer: while (!match) {
            if (now > waitformaxcap) {
                throw new Exception("Got bored, Quitting.");
            }
            now = now + START_SLEEP_TIME;

            try {

                List<String> params = new ArrayList<String>();
                List<ReservationDescription> instances = ec2.describeInstances(params);
                for (ReservationDescription res : instances) {
                    if (res.getInstances() != null) {
                        HashSet<InstanceP> instancesP = new HashSet<InstanceP>();
                        for (Instance inst : res.getInstances()) {
                            logger.info(inst.getInstanceId() + " " + orig_compute.getInstanceId() + " "
                                    + inst.getDnsName() + " " + addressInfoP.getPublicIp());
                            if (inst.getInstanceId().equals(orig_compute.getInstanceId())
                                    && inst.getDnsName().equals(addressInfoP.getPublicIp())) {
                                match = true;
                                break outer;
                            }

                        } //for (Instance inst : res.getInstances()) {
                    } //if (res.getInstances() != null) {
                } //for (ReservationDescription res : instances) {

                logger.info("Ipaddress " + addressInfoP.getPublicIp() + " getting associated; sleeping "
                        + START_SLEEP_TIME + "ms");
                Thread.sleep(START_SLEEP_TIME);

            } catch (Exception e) {
                logger.error(e);//e.printStackTrace();
                //addressInfoLocal=null;
                if (e.getMessage().indexOf("Number of retries exceeded") > -1) {
                    throw new Exception("No Connectivity to Cloud");
                }
            }
        }
        if (match == true) {
            try {
                orig_compute.setDnsName(addressInfoP.getPublicIp());
                orig_compute.merge();
            } catch (Exception e) {
                logger.error(e);//e.printStackTrace();
            }

            try {
                addressInfoP4PublicIp.setAssociated(true);
                addressInfoP4PublicIp.setInstanceId(orig_compute.getInstanceId());
                addressInfoP4PublicIp.setStatus(Commons.ipaddress_STATUS.associated + "");
                addressInfoP4PublicIp.merge();
            } catch (Exception e) {
                logger.error(e);//e.printStackTrace();
            }

            try {
                addressInfoP4InstanceId.setAssociated(false);
                addressInfoP4InstanceId.setInstanceId("somebody");
                addressInfoP4InstanceId.setStatus(Commons.ipaddress_STATUS.associated + "");
                addressInfoP4InstanceId.merge();
            } catch (Exception e) {
                logger.error(e);//e.printStackTrace();
            }
        }

    } catch (Exception e) {
        logger.error(e);//e.printStackTrace();
        try {
            AddressInfoP a = AddressInfoP.findAddressInfoP(addressInfoP.getId());
            a.setStatus(Commons.ipaddress_STATUS.failed + "");
            a = a.merge();
            setAssetEndTime(a.getAsset());
        } catch (Exception e2) {
            // TODO: handle exception
        }
    }

}

From source file:com.wso2.code.quality.matrices.ChangesFinder.java

/**
 * This method is used to save the line ranges being modified in a given file to a list and add that list to the root list of
 *
 * @param fileNames   Arraylist of files names that are being affected by the relevant commit
 * @param patchString Array list having the patch string value for each of the file being changed
 *//*from w  w  w . j  av  a 2 s .c o m*/

public void saveRelaventEditLineNumbers(ArrayList<String> fileNames, ArrayList<String> patchString) {
    //filtering only the line ranges that are modified and saving to a string array

    // cannot ues parallel streams here as the order of the line changes must be preserved
    patchString.stream().map(patch -> StringUtils.substringsBetween(patch, "@@ ", " @@"))
            .forEach(lineChanges -> {
                //filtering the lines ranges that existed in the previous file, that exists in the new file and saving them in to the same array
                IntStream.range(0, lineChanges.length).forEach(j -> {
                    //@@ -22,7 +22,7 @@ => -22,7 +22,7 => 22,28/22,28
                    String tempString = lineChanges[j];
                    String lineRangeInTheOldFileBeingModified = StringUtils.substringBetween(tempString, "-",
                            " +"); // for taking the authors and commit hashes of the previous lines
                    String lineRangeInTheNewFileResultedFromModification = StringUtils
                            .substringAfter(tempString, "+"); // for taking the parent commit

                    int intialLineNoInOldFile = Integer
                            .parseInt(StringUtils.substringBefore(lineRangeInTheOldFileBeingModified, ","));
                    int tempEndLineNoInOldFile = Integer
                            .parseInt(StringUtils.substringAfter(lineRangeInTheOldFileBeingModified, ","));
                    int endLineNoOfOldFile;
                    if (intialLineNoInOldFile != 0) {
                        // to filterout the newly created files
                        endLineNoOfOldFile = intialLineNoInOldFile + (tempEndLineNoInOldFile - 1);
                    } else {
                        endLineNoOfOldFile = tempEndLineNoInOldFile;
                    }
                    int intialLineNoInNewFile = Integer.parseInt(
                            StringUtils.substringBefore(lineRangeInTheNewFileResultedFromModification, ","));
                    int tempEndLineNoInNewFile = Integer.parseInt(
                            StringUtils.substringAfter(lineRangeInTheNewFileResultedFromModification, ","));
                    int endLineNoOfNewFile = intialLineNoInNewFile + (tempEndLineNoInNewFile - 1);
                    // storing the line ranges that are being modified in the same array by replacing values
                    lineChanges[j] = intialLineNoInOldFile + "," + endLineNoOfOldFile + "/"
                            + intialLineNoInNewFile + "," + endLineNoOfNewFile;
                });
                ArrayList<String> tempArrayList = new ArrayList<>(Arrays.asList(lineChanges));
                //adding to the array list which keep track of the line ranges being changed
                lineRangesChanged.add(tempArrayList);
            });
    System.out.println("done saving file names and their relevant modification line ranges");
    System.out.println(fileNames);
    System.out.println(lineRangesChanged + "\n");
}

From source file:mobi.jenkinsci.net.UrlPath.java

public String getPluginId() {
    final List<String> pathParts = getComponents();
    if (pathParts.size() <= 0) {
        return null;
    }//from www .ja  v a 2 s . co m
    final String firstPath = pathParts.get(0);
    return firstPath.indexOf("$") >= 0 ? StringUtils.substringBefore(firstPath, "$") : null;
}

From source file:com.ween.learn.util.excel.ImportExcel.java

/**
 * ??//from ww w  .  j a va  2 s.c o m
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, f });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, f });
            }
        }
    }
    // Get annotation method
    Method[] ms = cls.getDeclaredMethods();
    for (Method m : ms) {
        ExcelField ef = m.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, m });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, m });
            }
        }
    }
    // Field sorting
    Collections.sort(annotationList, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
        };
    });
    //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 (Object[] os : annotationList) {
            Object val = this.getCellValue(row, column++);
            if (val != null) {
                ExcelField ef = (ExcelField) os[0];
                // Get param type and type cast
                Class<?> valType = Class.class;
                if (os[1] instanceof Field) {
                    valType = ((Field) os[1]).getType();
                } else if (os[1] instanceof Method) {
                    Method method = ((Method) os[1]);
                    if ("get".equals(method.getName().substring(0, 3))) {
                        valType = method.getReturnType();
                    } else if ("set".equals(method.getName().substring(0, 3))) {
                        valType = ((Method) os[1]).getParameterTypes()[0];
                    }
                }
                //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);
                    } else {
                        if (ef.fieldType() != Class.class) {
                            val = ef.fieldType().getMethod("getValue", String.class).invoke(null,
                                    val.toString());
                        } else {
                            val = Class
                                    .forName(this.getClass().getName().replaceAll(
                                            this.getClass().getSimpleName(),
                                            "fieldtype." + valType.getSimpleName() + "Type"))
                                    .getMethod("getValue", String.class).invoke(null, val.toString());
                        }
                    }
                } catch (Exception ex) {
                    log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
                    val = null;
                }
                // set entity value
                if (os[1] instanceof Field) {
                    Reflections.invokeSetter(e, ((Field) os[1]).getName(), val);
                } else if (os[1] instanceof Method) {
                    String mthodName = ((Method) os[1]).getName();
                    if ("get".equals(mthodName.substring(0, 3))) {
                        mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
                    }
                    Reflections.invokeMethod(e, mthodName, new Class[] { valType }, new Object[] { val });
                }
            }
            sb.append(val + ", ");
        }
        dataList.add(e);
        log.debug("Read success: [" + i + "] " + sb.toString());
    }
    return dataList;
}

From source file:com.mgmtp.jfunk.core.mail.MailAccountManager.java

private MailAccount reserveAvailableMailAccount(final String accountReservationKey,
        final List<MailAccount> addressPool) {
    checkNotNull(accountReservationKey, "'accountReservationKey' must not be null");
    checkNotNull(addressPool, "'addressPool' must not be null");
    checkState(emailAddressPools.keySet().size() > 0, "'addressPool' must not be empty.");

    lock.lock();/*from w  w w.j a v  a  2  s.  co m*/
    try {
        while (true) {
            String fixedAccountId = config.get("mail." + accountReservationKey + ".accountId");

            MailAccount account = lookupUsedMailAccountForCurrentThread(accountReservationKey);
            if (!isNullOrEmpty(fixedAccountId)) {
                if (account != null) {
                    checkState(account.getAccountId().equals(fixedAccountId),
                            "Fixed configured mail account does not match that already reserved (configured=%s, reserved=%s)",
                            fixedAccountId, account.getAccountId());
                } else {
                    account = lookupMailAccount(fixedAccountId);
                    if (isReserved(account)) {
                        // Already reserved by another thread, so we cannot use it.
                        // Set it to null in order to trigger the wait below.
                        account = null;
                    }
                }
            } else {
                checkState(!addressPool.isEmpty(),
                        "No fixed e-mail account configured and specified pool is empty.");

                boolean subaddressing = config.getBoolean(EmailConstants.MAIL_SUBADDRESSING);
                if (subaddressing) {
                    checkState(addressPool.size() == 1,
                            "Mail subaddressing is active, specified pool must contain only one e-mail account.");
                }
                if (account != null) {
                    checkState(addressPool.contains(account), "Account '%s' is already reserved under key: %s",
                            account, accountReservationKey);
                    log.info("Using already reserved e-mail account: {}", account.getAccountId());
                    return account;
                }

                if (subaddressing) {
                    MailAccount acc = addressPool.get(0);
                    MailAuthenticator auth = (MailAuthenticator) acc.getAuthenticator();

                    StringBuilder uniqueAddress = new StringBuilder();
                    uniqueAddress.append(StringUtils.substringBefore(acc.getAddress(), "@"));
                    uniqueAddress.append("+");
                    uniqueAddress.append(UUID.randomUUID());
                    uniqueAddress.append("@");
                    uniqueAddress.append(StringUtils.substringAfter(acc.getAddress(), "@"));

                    account = new MailAccount(acc.getAccountId(), uniqueAddress.toString(), auth.getUser(),
                            auth.getPassword());
                } else {
                    // Try to find a free account.
                    for (MailAccount acc : addressPool) {
                        ThreadReservationKeyWrapper wrapper = usedAccounts.get(acc);
                        if (wrapper == null) {
                            account = acc;
                            break;
                        }
                    }
                }
            }

            if (account == null) {
                // No free account available. We wait and then start over with the loop.
                log.info("No free e-mail account available. Waiting...");
                condition.await();
            } else {
                // We've found a free account and return it.
                String accountId = account.getAccountId();
                log.info("Found free e-mail account={} with address={}", accountId, account.getAddress());

                usedAccounts.put(account,
                        new ThreadReservationKeyWrapper(Thread.currentThread(), accountReservationKey));

                // post account reservation
                eventBusProvider.get().post(new MailAccountReservationEvent(accountReservationKey, account));

                return account;
            }
        }
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new JFunkException(ex.getMessage(), ex);
    } finally {
        lock.unlock();
    }
}

From source file:de.blizzy.documentr.markdown.MarkdownProcessor.java

public String processNonCacheableMacros(String html, String projectName, String branchName, String path,
        Authentication authentication, String contextPath) {

    HtmlSerializerContext context = new HtmlSerializerContext(projectName, branchName, path, this,
            authentication, pageStore, systemSettingsStore, contextPath);
    String startMarkerPrefix = "__" + NON_CACHEABLE_MACRO_MARKER + "_"; //$NON-NLS-1$ //$NON-NLS-2$
    String endMarkerPrefix = "__/" + NON_CACHEABLE_MACRO_MARKER + "_"; //$NON-NLS-1$ //$NON-NLS-2$
    String bodyMarker = "__" + NON_CACHEABLE_MACRO_BODY_MARKER + "__"; //$NON-NLS-1$ //$NON-NLS-2$
    for (;;) {/*from   w w w  .j av  a2 s . c  o m*/
        int start = html.indexOf(startMarkerPrefix);
        if (start < 0) {
            break;
        }
        start += startMarkerPrefix.length();

        int end = html.indexOf('_', start);
        if (end < 0) {
            break;
        }
        String idx = html.substring(start, end);

        start = html.indexOf("__", start); //$NON-NLS-1$
        if (start < 0) {
            break;
        }
        start += 2;

        end = html.indexOf(endMarkerPrefix + idx + "__", start); //$NON-NLS-1$
        if (end < 0) {
            break;
        }

        String macroCallWithBody = html.substring(start, end);
        String macroCall = StringUtils.substringBefore(macroCallWithBody, bodyMarker);
        String body = StringUtils.substringAfter(macroCallWithBody, bodyMarker);
        String macroName = StringUtils.substringBefore(macroCall, " "); //$NON-NLS-1$
        String params = StringUtils.substringAfter(macroCall, " "); //$NON-NLS-1$
        IMacro macro = macroFactory.get(macroName);
        MacroContext macroContext = MacroContext.create(macroName, params, body, context, beanFactory);
        IMacroRunnable macroRunnable = macro.createRunnable();

        html = StringUtils.replace(html,
                startMarkerPrefix + idx + "__" + macroCallWithBody + endMarkerPrefix + idx + "__", //$NON-NLS-1$ //$NON-NLS-2$
                StringUtils.defaultString(macroRunnable.getHtml(macroContext)));

        MacroInvocation invocation = new MacroInvocation(macroName, params);
        html = cleanupHtml(html, Collections.singletonList(invocation), false);
    }
    return html;
}

From source file:com.gargoylesoftware.htmlunit.html.XmlSerializer.java

/**
 * Computes the best file to save the response to the given URL.
 * @param url the requested URL/*from   w  ww  .java 2 s .  co  m*/
 * @param extension the preferred extension
 * @return the file to create
 * @throws IOException if a problem occurs creating the file
 */
private File createFile(final String url, final String extension) throws IOException {
    String name = url.replaceFirst("/$", "");
    name = CREATE_FILE_PATTERN.matcher(name).replaceAll("");
    name = StringUtils.substringBefore(name, "?"); // remove query
    name = StringUtils.substringBefore(name, ";"); // remove additional info
    name = StringUtils.substring(name, 0, 30); // many file systems have a limit at 255, let's limit it
    name = com.gargoylesoftware.htmlunit.util.StringUtils.sanitizeForFileName(name);
    if (!name.endsWith(extension)) {
        name += extension;
    }
    int counter = 0;
    while (true) {
        final String fileName;
        if (counter != 0) {
            fileName = StringUtils.substringBeforeLast(name, ".") + "_" + counter + "."
                    + StringUtils.substringAfterLast(name, ".");
        } else {
            fileName = name;
        }
        outputDir_.mkdirs();
        final File f = new File(outputDir_, fileName);
        if (f.createNewFile()) {
            return f;
        }
        counter++;
    }
}