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

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

Introduction

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

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.baoqilai.core.util.WebUtils.java

/**
 * ?contentTypeheaders./*from   w  w  w .  ja v  a 2s .  com*/
 */
private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
    // ?headers?
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
        String headerName = StringUtils.substringBefore(header, ":");
        String headerValue = StringUtils.substringAfter(header, ":");

        if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
            encoding = headerValue;
        } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
            noCache = Boolean.parseBoolean(headerValue);
        } else {
            throw new IllegalArgumentException(headerName + "??header");
        }
    }

    HttpServletResponse response = ServletActionContext.getResponse();

    // headers?
    String fullContentType = contentType + ";charset=" + encoding;
    response.setContentType(fullContentType);
    if (noCache) {
        setDisableCacheHeader(response);
    }

    return response;
}

From source file:com.opengamma.component.factory.engine.EngineConfigurationComponentFactory.java

protected void buildConfiguration(final ComponentRepository repo, final Map<String, String> configuration,
        final Map<String, Object> map) {
    map.put(LOGICAL_SERVER_UNIQUE_IDENTIFIER, getLogicalServerId());
    for (final String key : configuration.keySet()) {
        final String valueStr = configuration.get(key);
        Object targetValue = valueStr;
        if (valueStr.contains("::")) {
            final String type = StringUtils.substringBefore(valueStr, "::");
            final String classifier = StringUtils.substringAfter(valueStr, "::");
            final ComponentInfo info = repo.findInfo(type, classifier);
            if (info == null) {
                throw new IllegalArgumentException("Component not found: " + valueStr);
            }/*from  w w w .ja  v a 2  s  . c o m*/
            final Object instance = repo.getInstance(info);
            if ((instance instanceof CalcNodeSocketConfiguration) || (instance instanceof Supplier)) {
                targetValue = instance;
            } else {
                if (info.getUri() == null) {
                    throw new OpenGammaRuntimeException(
                            "Unable to add component to configuration as it has not been published by REST: "
                                    + valueStr);
                }
                targetValue = new UriEndPointDescriptionProvider(info.getUri().toString());
            }
        }
        buildMap(map, key, targetValue);
    }
}

From source file:net.itransformers.idiscover.v2.core.node_discoverers.snmpdiscoverer.SnmpSequentialNodeDiscoverer.java

@Override
public NodeDiscoveryResult discover(ConnectionDetails connectionDetails) {
    Map<String, String> params1 = new HashMap<String, String>();
    String deviceName = connectionDetails.getParam("deviceName");

    NodeDiscoveryResult result = new NodeDiscoveryResult();

    if (deviceName != null && !deviceName.isEmpty()) {
        params1.put("deviceName", deviceName);

    }//  ww  w .j  av a2s.  c o m
    String deviceType = connectionDetails.getParam("deviceType");
    if (deviceType != null && !deviceType.isEmpty()) {
        params1.put("deviceType", deviceType);

    }
    String ipAddressStr = connectionDetails.getParam("ipAddress");

    if (ipAddressStr != null && !ipAddressStr.isEmpty()) {
        params1.put("ipAddress", ipAddressStr);

    }
    String dnsCanonicalName = null;
    String dnsShortName = null;
    InetAddress inetAddress = null;
    SnmpManager snmpManager = null;
    Map<String, String> snmpConnParams = new HashMap<String, String>();

    ResourceType snmpResource = this.discoveryResource.returnResourceByParam(params1);
    List<ResourceType> snmpResources = this.discoveryResource.returnResourcesByConnectionType("snmp");
    String sysDescr;
    snmpConnParams = this.discoveryResource.getParamMap(snmpResource, "snmp");
    snmpConnParams.put("ipAddress", ipAddressStr);
    boolean reachable;
    SnmpManagerCreator snmpManagerCreator = new SnmpManagerCreator(mibLoaderHolder);

    try {
        reachable = inetAddress.isReachable(Integer.parseInt(snmpConnParams.get("timeout")));
        logger.info("Device with " + inetAddress.getHostAddress() + "is " + reachable);
        //Try first with the most probable snmp Resource
        snmpManager = snmpManagerCreator.create(snmpConnParams);
        snmpManager.init();
        sysDescr = snmpGet(snmpManager, "1.3.6.1.2.1.1.1.0");

        //If it does not work try with the rest

        if (sysDescr == null) {
            snmpManager.closeSnmp();
            logger.info("Can't connect to: " + ipAddressStr + " with " + snmpConnParams);

            for (ResourceType resourceType : snmpResources) {
                snmpConnParams = this.discoveryResource.getParamMap(resourceType, "snmp");
                snmpConnParams.put("ipAddress", ipAddressStr);

                if (!resourceType.getName().equals(snmpResource.getName())) {

                    snmpManager = snmpManagerCreator.create(snmpConnParams);
                    snmpManager.init();
                    sysDescr = snmpGet(snmpManager, "1.3.6.1.2.1.1.1.0");
                    if (sysDescr == null) {
                        logger.info("Can't connect to: " + ipAddressStr + " with " + snmpConnParams);
                        snmpManager.closeSnmp();
                    } else {
                        deviceType = DeviceTypeResolver.getDeviceType(sysDescr);
                        logger.info("Connected to: " + ipAddressStr + " with " + snmpConnParams);
                        deviceName = StringUtils.substringBefore(snmpGet(snmpManager, "1.3.6.1.2.1.1.5.0"),
                                ".");
                        break;
                    }
                }
            }
        } else {
            deviceType = DeviceTypeResolver.getDeviceType(sysDescr);
            logger.info("Connected to: " + ipAddressStr + " with " + snmpConnParams);
            deviceName = StringUtils.substringBefore(snmpGet(snmpManager, "1.3.6.1.2.1.1.5.0"), ".");
        }
    } catch (IOException e) {
        logger.error("Something went wrong in SNMP communication with " + ipAddressStr
                + ":Check the stacktrace \n" + e.getStackTrace());
        return null;
    }

    //Despite all our efforts we got nothing from that device!
    if (sysDescr == null) {
        if (deviceName != null) {
            result = new NodeDiscoveryResult(deviceName, null, null);
        } else if (dnsCanonicalName != null) {
            result = new NodeDiscoveryResult(dnsShortName, null, null);
        } else {
            result = new NodeDiscoveryResult(ipAddressStr, null, null);
        }

        return result;
    }
    DiscoveryHelper discoveryHelper = discoveryHelperFactory.createDiscoveryHelper(deviceType);
    String[] requestParamsList = discoveryHelper.getRequestParams(discoveryTypes);

    Node rawDatNode = null;
    net.itransformers.idiscover.api.models.node_data.RawDeviceData rawData = null;
    try {
        rawDatNode = snmpManager.snmpWalk(requestParamsList);
        snmpManager.closeSnmp();

    } catch (IOException e) {
        e.printStackTrace();
    }
    if (rawDatNode != null) {
        SnmpXmlPrinter snmpXmlPrinter = new SnmpXmlPrinter(mibLoaderHolder.getLoader(), rawDatNode);
        rawData = new net.itransformers.idiscover.api.models.node_data.RawDeviceData(
                snmpXmlPrinter.printTreeAsXML().getBytes());

        logger.trace(new String(rawData.getData()));

    } else {

        return null;
    }
    SnmpForXslt.setMibLoaderHolder(mibLoaderHolder);
    snmpConnParams.put("neighbourIPDryRun", "true");
    discoveryHelper.parseDeviceRawData(rawData, discoveryTypes, snmpConnParams);

    SnmpForXslt.resolveIPAddresses(discoveryResource, "snmp");
    snmpConnParams.put("neighbourIPDryRun", "false");

    DiscoveredDeviceData discoveredDeviceData = discoveryHelper.parseDeviceRawData(rawData, discoveryTypes,
            snmpConnParams);

    Device device = discoveryHelper.createDevice(discoveredDeviceData);

    List<DeviceNeighbour> neighbours = device.getDeviceNeighbours();
    Set<Subnet> subnets = device.getDeviceSubnets();
    Set<ConnectionDetails> neighboursConnDetails = null;
    if (neighbours != null) {

        //TODO adapt for new algorthm and new DiscoveredDevice
        NeighbourConnectionDetails neighbourConnectionDetails = null;
        neighboursConnDetails = neighbourConnectionDetails.getConnectionDetailses();
    }

    Set<ConnectionDetails> subnetConnectionDetails = null;

    if (subnets != null) {
        SubnetConnectionDetails subnetConnectionDetailsCreator = new SubnetConnectionDetails();
        subnetConnectionDetailsCreator.load(subnets);
        neighboursConnDetails.addAll(subnetConnectionDetails);

    }

    //TODO add also own connectionDetails
    result = new NodeDiscoveryResult(deviceName, neighboursConnDetails, null);
    result.setDiscoveredData("deviceData", discoveredDeviceData);
    result.setDiscoveredData("rawData", rawData.getData());
    return result;
}

From source file:com.alibaba.otter.shared.common.model.config.ConfigHelper.java

public static String makeSQLPattern(ModeValue mode, String rawValue) {
    Assert.notNull(mode);// w  w  w  . ja va  2  s .  c o  m
    Assert.notNull(rawValue);
    if (mode.getMode().isSingle()) {
        return rawValue;
    } else if (mode.getMode().isMulti()) {
        return StringUtils.substringBefore(rawValue, "[") + "%";
    } else if (mode.getMode().isWildCard()) {
        StringBuilder sb = new StringBuilder(rawValue.length());
        FOR_LOOP: for (int i = 0; i < rawValue.length(); i++) {
            String charString = String.valueOf(rawValue.charAt(i));
            if (isWildCard(charString)) {
                break FOR_LOOP;
            } else {
                sb.append(rawValue.charAt(i));
            }
        }
        return sb.toString() + "%";
    } else {
        throw new UnsupportedOperationException("unsupport mode:" + mode.getMode());
    }
}

From source file:com.streamsets.pipeline.lib.parser.log.ExtendedFormatParser.java

void putLabelIntoAppropriateMap(Map<String, String> labelMap, Map<String, Field> extMap, String key,
        String value) {/*from  ww  w  .j  a v  a2 s.c  o m*/
    if (key.endsWith("Label")) {
        labelMap.put(StringUtils.substringBefore(key, "Label"), value);
    } else {
        extMap.put(key, Field.create(value));
    }
}

From source file:com.intellij.lang.jsgraphql.ide.annotator.JSGraphQLAnnotator.java

@Override
public void apply(@NotNull PsiFile file, JSGraphQLAnnotationResult annotationResult,
        @NotNull AnnotationHolder holder) {
    if (annotationResult != null) {
        try {/*from w w  w.  j  a  v  a  2s . c o m*/
            final Editor editor = annotationResult.getEditor();
            final String fileName = file.getVirtualFile().getPath();
            final List<JSGraphQLErrorResult> errors = Lists.newArrayList();
            final JSGraphQLLanguageWarningAnnotator internalAnnotator = new JSGraphQLLanguageWarningAnnotator();
            file.accept(new PsiRecursiveElementVisitor() {
                @Override
                public void visitElement(PsiElement element) {
                    final com.intellij.lang.annotation.Annotation annotation = internalAnnotator.annotate(file,
                            element, holder);
                    if (annotation != null) {
                        final LogicalPosition pos = editor.offsetToLogicalPosition(element.getTextOffset());
                        errors.add(new JSGraphQLErrorResult(annotation.getMessage(), fileName,
                                annotation.getSeverity().myName, pos.line + 1, pos.column + 1));
                    }
                    super.visitElement(element);
                }
            });
            AnnotationsResponse annotationsReponse = annotationResult.getAnnotationsReponse();
            if (annotationsReponse == null) {
                return;
            }
            for (Annotation annotation : annotationsReponse.getAnnotations()) {
                LogicalPosition from = getLogicalPosition(annotation.getFrom());
                LogicalPosition to = getLogicalPosition(annotation.getTo());
                int fromOffset = editor.logicalPositionToOffset(from);
                int toOffset = editor.logicalPositionToOffset(to);
                HighlightSeverity severity = "error".equals(annotation.getSeverity()) ? HighlightSeverity.ERROR
                        : HighlightSeverity.WARNING;
                if (fromOffset < toOffset) {
                    final String message = StringUtils.substringBefore(annotation.getMessage(), "\n");
                    holder.createAnnotation(severity, TextRange.create(fromOffset, toOffset), message);
                    errors.add(new JSGraphQLErrorResult(message, fileName, annotation.getSeverity(),
                            from.line + 1, from.column + 1)); // +1 is for UI lines/columns
                }
            }
            JSGraphQLLanguageUIProjectService jsGraphQLLanguageUIProjectService = JSGraphQLLanguageUIProjectService
                    .getService(file.getProject());
            if (jsGraphQLLanguageUIProjectService != null) {
                jsGraphQLLanguageUIProjectService.logErrorsInCurrentFile(file, errors);
            }
        } catch (Exception e) {
            log.error("Unable to apply annotations", e);
        } finally {
            annotationResult.releaseEditor();
        }
    }
}

From source file:gobblin.data.management.retention.sql.SqlBasedRetentionPoc.java

private void insertSnapshot(Path snapshotPath) throws Exception {

    String datasetPath = StringUtils.substringBeforeLast(snapshotPath.toString(), Path.SEPARATOR);
    String snapshotName = StringUtils.substringAfterLast(snapshotPath.toString(), Path.SEPARATOR);
    long ts = Long.parseLong(StringUtils.substringBefore(snapshotName, "-PT-"));
    long recordCount = Long.parseLong(StringUtils.substringAfter(snapshotName, "-PT-"));

    PreparedStatement insert = connection.prepareStatement("INSERT INTO Snapshots VALUES (?, ?, ?, ?, ?)");
    insert.setString(1, datasetPath);//from   w w w .  j  av a 2  s .  com
    insert.setString(2, snapshotName);
    insert.setString(3, snapshotPath.toString());
    insert.setTimestamp(4, new Timestamp(ts));
    insert.setLong(5, recordCount);

    insert.executeUpdate();

}

From source file:cec.easyshop.storefront.interceptors.beforecontroller.RequireHardLoginBeforeControllerHandler.java

protected boolean checkForAnonymousCheckout() {
    if (Boolean.TRUE.equals(getSessionService().getAttribute(WebConstants.ANONYMOUS_CHECKOUT))) {
        if (getSessionService().getAttribute(WebConstants.ANONYMOUS_CHECKOUT_GUID) == null) {
            getSessionService().setAttribute(WebConstants.ANONYMOUS_CHECKOUT_GUID,
                    StringUtils.substringBefore(getCartService().getSessionCart().getUser().getUid(), "|"));
        }/*from   w w w. j a  v a  2  s  . c  o m*/
        return true;
    }
    return false;
}

From source file:com.hangum.tadpole.rdb.core.editors.main.function.MainEditorBrowserFunctionService.java

/**
 * parse last object /*from  w  w  w . j a  v  a 2  s  .c o  m*/
 */
private String parseLastObject(String obj) {
    String strObject = StringUtils.remove((String) obj, ",");
    if (StringUtils.contains(strObject, '(')) {
        strObject = StringUtils.substringBefore(strObject, "(");
    }

    if (StringUtils.contains(strObject, ')')) {
        strObject = StringUtils.substringAfter(strObject, ")");
    }

    return strObject;
}

From source file:com.lakeside.data.sqldb.PageBaseDao.java

protected <X> String setOrder(final String hql, final Page<X> page) {
    if (!page.isOrderBySetted()) {
        return hql;
    }//ww w .  ja v a2s  .c o m
    String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
    String[] orderArray = StringUtils.split(page.getOrder(), ',');

    Assert.isTrue(orderByArray.length == orderArray.length,
            "???,????");
    StringBuilder orderSql = new StringBuilder(StringUtils.substringBefore(hql, "order by"));

    orderSql.append("order by ");
    for (int i = 0; i < orderByArray.length; i++) {
        orderSql.append(orderByArray[i]).append(" ").append(orderArray[i]).append(",");
    }
    return orderSql.substring(0, orderSql.length() - 1);
}