Java Code Examples for org.apache.commons.lang.StringUtils#substringAfterLast()

The following examples show how to use org.apache.commons.lang.StringUtils#substringAfterLast() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: DBus   File: ProjectCheckHeartBeatEvent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 从path中提取信息,放入node中
 *
 * @param node
 * @param path     原始path: /DBus/HeartBeat/ProjectMonitor/project1/topo1/ds1.schema1.table1
 * @param basePath
 * @return
 */
private ProjectMonitorNodeVo initNodeAttribute(ProjectMonitorNodeVo node, String path, String basePath) {
    //操作后path:project1/topo1/ds1.schema1.table1
    path = StringUtils.replace(path, basePath + "/", StringUtils.EMPTY);

    //projectTopoName:project1/topo1
    String projectTopoName = StringUtils.substringBeforeLast(path, "/");
    node.setProjectName(StringUtils.substringBeforeLast(projectTopoName, "/"));
    node.setTopoName(StringUtils.substringAfterLast(projectTopoName, "/"));

    //ds1.schema1.table1
    String leafNodeName = StringUtils.substringAfterLast(path, "/");
    node.setTableName(StringUtils.substringAfterLast(path, "."));

    //ds1.schema1
    String datasourceSchemaName = StringUtils.substringBeforeLast(leafNodeName, ".");
    node.setDsName(StringUtils.substringBefore(datasourceSchemaName, "."));
    node.setSchema(StringUtils.substringAfter(datasourceSchemaName, "."));

    LOG.info(MsgUtil.format("node info: project: {0}, topo: {1}, ds: {2}, schema: {3}, table: {4}",
            node.getProjectName(), node.getTopoName(), node.getDsName(), node.getSchema(), node.getTableName()));
    return node;
}
 
Example 2
/**
 * Logs the event type and some information about the associated item
 */
private void logEvent() {
    StringBuffer logMessage = new StringBuffer(StringUtils.substringAfterLast(this.getClass().getName(), "."));
    logMessage.append(" with ");

    // vary logging detail as needed
    if (item == null) {
        logMessage.append("null item");
    }
    else {
        logMessage.append(" item# ");
        logMessage.append(item.getItemIdentifier());
    }

    LOG.debug(logMessage);
}
 
Example 3
/**
 * 异常处理,定义返回报文格式
 */
@Override
protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
    Throwable error = super.getError(request);
    log.error(
            "请求发生异常,请求URI:{},请求方法:{},异常信息:{}",
            request.path(), request.methodName(), error.getMessage()
    );
    String errorMessage;
    if (error instanceof NotFoundException) {
        String serverId = StringUtils.substringAfterLast(error.getMessage(), "Unable to find instance for ");
        serverId = StringUtils.replace(serverId, "\"", StringUtils.EMPTY);
        errorMessage = String.format("无法找到%s服务", serverId);
    } else if (StringUtils.containsIgnoreCase(error.getMessage(), "connection refused")) {
        errorMessage = "目标服务拒绝连接";
    } else if (error instanceof TimeoutException) {
        errorMessage = "访问服务超时";
    } else if (error instanceof ResponseStatusException
            && StringUtils.containsIgnoreCase(error.getMessage(), HttpStatus.NOT_FOUND.toString())) {
        errorMessage = "未找到该资源";
    } else {
        errorMessage = "网关转发异常";
    }
    Map<String, Object> errorAttributes = new HashMap<>(2);
    errorAttributes.put("msg", errorMessage);
    errorAttributes.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
    return errorAttributes;
}
 
Example 4
Source Project: sofa-acts   File: ArrayTypeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String generateObjectValue(Object obj, String csvPath, boolean isSimple) {
    String collectionString = "";

    if (Array.getLength(obj) == 0) {
        collectionString = "@[email protected]";
        return collectionString;
    }

    if (isSimple) {
        for (int i = 0; i < Array.getLength(obj); i++) {
            collectionString = collectionString + String.valueOf(Array.get(obj, i)) + ";";
        }
    } else {
        String reCsvPath = StringUtils.substringAfterLast(csvPath, "/");
        collectionString = reCsvPath + "@";
        for (int i = 0; i < Array.getLength(obj); i++) {
            try {
                int index = CSVHelper.insertObjDataAndReturnIndex(Array.get(obj, i), csvPath);
                collectionString = collectionString + String.valueOf(index) + ";";
            } catch (Exception e) {
                LOG.error("Cann't convert array to string!", e);
                return null;
            }
        }
    }
    collectionString = collectionString.substring(0, collectionString.length() - 1);
    return collectionString;
}
 
Example 5
public String getSimpleName() {
    String simpleName = StringUtils.substringAfterLast(name, ".");
    if (simpleName.equals("")) {
        return name;
    }
    return simpleName;
}
 
Example 6
public ArtifactFile(File file, String version) {
    name = file.getName();
    extension = "";
    classifier = "";
    boolean done = false;

    int startVersion = StringUtils.lastIndexOf(name, "-" + version);
    if (startVersion >= 0) {
        int endVersion = startVersion + version.length() + 1;
        if (endVersion == name.length()) {
            name = name.substring(0, startVersion);
            done = true;
        } else if (endVersion < name.length() && name.charAt(endVersion) == '-') {
            String tail = name.substring(endVersion + 1);
            name = name.substring(0, startVersion);
            classifier = StringUtils.substringBeforeLast(tail, ".");
            extension = StringUtils.substringAfterLast(tail, ".");
            done = true;
        } else if (endVersion < name.length() && StringUtils.lastIndexOf(name, ".") == endVersion) {
            extension = name.substring(endVersion + 1);
            name = name.substring(0, startVersion);
            done = true;
        }
    }
    if (!done) {
        extension = StringUtils.substringAfterLast(name, ".");
        name = StringUtils.substringBeforeLast(name, ".");
    }
    if (extension.length() == 0) {
        extension = null;
    }
    if (classifier.length() == 0) {
        classifier = null;
    }
}
 
Example 7
Source Project: spring-boot   File: MySystemUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取IP地址
 * 
 * @return
 */
public static String getIpAddress() {
	String ip = "";
	try {
		// ip:apollonotebook/192.168.1.2
		String address = InetAddress.getLocalHost().toString();
		// System.out.println(address);
		ip = StringUtils.substringAfterLast(address, "/");
		// System.out.println(ip);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return ip;
}
 
Example 8
public void getJarFromCP() {
   try {
      Enumeration resEnum = Thread.currentThread().getContextClassLoader().getResources("META-INF/MANIFEST.MF");
      String[] cpElements = ArrayUtils.EMPTY_STRING_ARRAY;

      while(resEnum.hasMoreElements()) {
         URL url = (URL)resEnum.nextElement();
         StringBuilder sb = new StringBuilder("[CP Content] ");
         String substringAfterLast = StringUtils.substringAfterLast(StringUtils.substringBefore(url.getPath(), "!"), "/");
         if (!"MANIFEST.MF".equals(substringAfterLast)) {
            sb.append(substringAfterLast);
            cpElements = (String[])((String[])ArrayUtils.add(cpElements, sb.toString()));
         }
      }

      Arrays.sort(cpElements);
      String[] arr$ = cpElements;
      int len$ = cpElements.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         String cpElement = arr$[i$];
         LOG.debug(cpElement);
      }
   } catch (IOException var7) {
      LOG.error(var7.getMessage(), var7);
   }

}
 
Example 9
/**
 * Returns the primitive part of an attribute name string.
 *
 * @param attributeName
 * @return everything AFTER the last "." character in attributeName
 */
public static String getNestedAttributePrimitive(String attributeName) {
    String primitive = attributeName;

    if (StringUtils.contains(attributeName, ".")) {
        primitive = StringUtils.substringAfterLast(attributeName, ".");
    }

    return primitive;
}
 
Example 10
public void getJarFromCP() {
   try {
      Enumeration resEnum = Thread.currentThread().getContextClassLoader().getResources("META-INF/MANIFEST.MF");
      String[] cpElements = ArrayUtils.EMPTY_STRING_ARRAY;

      while(resEnum.hasMoreElements()) {
         URL url = (URL)resEnum.nextElement();
         StringBuilder sb = new StringBuilder("[CP Content] ");
         String substringAfterLast = StringUtils.substringAfterLast(StringUtils.substringBefore(url.getPath(), "!"), "/");
         if (!"MANIFEST.MF".equals(substringAfterLast)) {
            sb.append(substringAfterLast);
            cpElements = (String[])((String[])ArrayUtils.add(cpElements, sb.toString()));
         }
      }

      Arrays.sort(cpElements);
      String[] arr$ = cpElements;
      int len$ = cpElements.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         String cpElement = arr$[i$];
         LOG.debug(cpElement);
      }
   } catch (IOException var7) {
      LOG.error(var7.getMessage(), var7);
   }

}
 
Example 11
Resource addResource(URL source) {
    String name = StringUtils.substringAfterLast(source.getPath(), "/");
    String type = StringUtils.substringAfterLast(source.getPath(), ".");
    if (type.equalsIgnoreCase("png") || type.equalsIgnoreCase("gif")) {
        type = "images";
    }
    String path = String.format("%s/%s", type, name);
    Resource resource = resources.get(path);
    if (resource == null) {
        resource = new Resource(source, path);
        resources.put(path, resource);
    }
    return resource;
}
 
Example 12
Source Project: nifi   File: ValueReader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Set<FlowFile> readSequenceFile(final Path file, Configuration configuration, FileSystem fileSystem) throws IOException {

    Set<FlowFile> flowFiles = new HashSet<>();
    final SequenceFile.Reader reader = new SequenceFile.Reader(configuration, Reader.file(fileSystem.makeQualified(file)));
    final String inputfileName = file.getName() + "." + System.nanoTime() + ".";
    int counter = 0;
    LOG.debug("Reading from sequence file {}", new Object[]{file});
    final OutputStreamWritableCallback writer = new OutputStreamWritableCallback(reader);
    Text key = new Text();
    try {
        while (reader.next(key)) {
            String fileName = key.toString();
            // the key may be a file name, and may not
            if (LOOKS_LIKE_FILENAME.matcher(fileName).matches()) {
                if (fileName.contains(File.separator)) {
                    fileName = StringUtils.substringAfterLast(fileName, File.separator);
                }
                fileName = fileName + "." + System.nanoTime();
            } else {
                fileName = inputfileName + ++counter;
            }
            FlowFile flowFile = session.create();
            flowFile = session.putAttribute(flowFile, CoreAttributes.FILENAME.key(), fileName);
            try {
                flowFile = session.write(flowFile, writer);
                flowFiles.add(flowFile);
            } catch (ProcessException e) {
                LOG.error("Could not write to flowfile {}", new Object[]{flowFile}, e);
                session.remove(flowFile);
            }
            key.clear();
        }
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return flowFiles;
}
 
Example 13
Source Project: DBus   File: CheckFullPullEvent.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取全量拉取的最新节点
 *
 * @param fullPullerRootNode
 * @param curator
 * @return 子节点的全路径,之前非全路径,后面的path部分进行了拼接
 * @throws Exception
 */
private List<String> filter(String fullPullerRootNode, CuratorFramework curator) throws Exception {
    List<String> flattedFullpullerNodeName = new ArrayList<>();

    //get all node list
    fetchZkNodeRecursively(fullPullerRootNode, flattedFullpullerNodeName, curator);

    HashMap<String, String> map = new HashMap<>();
    for (String znode : flattedFullpullerNodeName) {
        String key = StringUtils.substringBeforeLast(znode, "/");
        String ver = StringUtils.substringAfterLast(znode, "/");
        if (map.containsKey(key)) {
            String tempVersion = map.get(key);
            if (ver.compareTo(tempVersion) > 0) {
                map.put(key, ver);
            }
        } else {
            map.put(key, ver);
        }
    }

    List<String> wkList = new ArrayList<String>();
    for (Map.Entry<String, String> entry : map.entrySet()) {
        wkList.add(StringUtils.join(new String[]{entry.getKey(), String.valueOf(entry.getValue())}, "/"));
    }
    return wkList;
}
 
Example 14
protected MavenArtifact parseFile(File file) {
    String extension = StringUtils.substringAfterLast(file.getName(), ".");
    return instantiator.newInstance(DefaultMavenArtifact.class, file, extension, null);
}
 
Example 15
@Override
public List<ProductListItem> getProducts() {
    if (productsRetriever == null) {
        return Collections.emptyList();
    }

    List<ProductInterface> products = productsRetriever.fetchProducts();
    Collections.sort(products, Comparator.comparing(item -> baseProductSkus.indexOf(item.getSku())));

    List<ProductListItem> carouselProductList = new ArrayList<>();
    if (!products.isEmpty()) {
        for (String combinedSku : productSkuList) {

            if (combinedSku.startsWith("/")) {
                combinedSku = StringUtils.substringAfterLast(combinedSku, "/");
            }

            Pair<String, String> skus = SiteNavigation.toProductSkus(combinedSku);
            ProductInterface product = products.stream().filter(p -> p.getSku().equals(skus.getLeft())).findFirst().orElse(null);
            if (product == null) {
                continue; // Can happen that a product is not found
            }

            String slug = product.getUrlKey();
            if (skus.getRight() != null && product instanceof ConfigurableProduct) {
                SimpleProduct variant = findVariant((ConfigurableProduct) product, skus.getRight());
                if (variant != null) {
                    product = variant;
                }
            }

            try {
                Price price = new PriceImpl(product.getPriceRange(), locale);
                ProductImage thumbnail = product.getThumbnail();
                carouselProductList.add(new ProductListItemImpl(
                    skus.getLeft(),
                    slug,
                    product.getName(),
                    price,
                    thumbnail == null ? null : thumbnail.getUrl(),
                    productPage,
                    skus.getRight(),
                    request,
                    urlProvider));
            } catch (Exception e) {
                LOGGER.error("Failed to instantiate product " + combinedSku, e);
            }
        }
    }
    return carouselProductList;
}
 
Example 16
protected MavenArtifact parseFile(File file) {
    String extension = StringUtils.substringAfterLast(file.getName(), ".");
    return instantiator.newInstance(DefaultMavenArtifact.class, file, extension, null);
}
 
Example 17
Source Project: APM   File: FileDescriptor.java    License: Apache License 2.0 4 votes vote down vote up
private static String getFileNameFromOriginalFileName(String originalFileName) {
  if (originalFileName.contains("/")) {
    return StringUtils.substringAfterLast(originalFileName, "/");
  }
  return originalFileName;
}
 
Example 18
public DaemonNamedThreadFactory(String name) {
  super(name + " " + StringUtils.substringAfterLast(_logger.getName(), "."));
}
 
Example 19
Source Project: symphonyx   File: AdminProcessor.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Shows admin point charge records.
 *
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @throws Exception exception
 */
@RequestProcessing(value = "/admin/charge-records", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, MallAdminCheck.class})
@After(adviceClass = {CSRFToken.class, StopwatchEndAdvice.class})
public void showChargeRecords(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("admin/charge-records.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();

    String pageNumStr = request.getParameter("p");
    if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
        pageNumStr = "1";
    }

    final int pageNum = Integer.valueOf(pageNumStr);
    final int pageSize = Symphonys.PAGE_SIZE;

    final JSONObject result = pointtransferQueryService.getChargeRecords(pageNum, pageSize);
    final List<JSONObject> results = (List<JSONObject>) result.opt(Keys.RESULTS);
    for (final JSONObject record : results) {
        final String toUserId = record.optString(Pointtransfer.TO_ID);
        final JSONObject toUser = userQueryService.getUser(toUserId);
        record.put(User.USER_NAME, toUser.optString(User.USER_NAME));
        record.put(UserExt.USER_REAL_NAME, toUser.optString(UserExt.USER_REAL_NAME));

        final String handlerId = StringUtils.substringAfterLast(record.optString(Pointtransfer.DATA_ID), "-");
        final JSONObject handler = userQueryService.getUser(handlerId);
        record.put(Common.HANDLER_NAME, handler.optString(User.USER_NAME));
        record.put(Common.HANDLER_REAL_NAME, handler.optString(UserExt.USER_REAL_NAME));

        record.put(Pointtransfer.TIME, new Date(record.optLong(Pointtransfer.TIME)));
        record.put(Common.MONEY, StringUtils.substringBefore(record.optString(Pointtransfer.DATA_ID), "-"));
    }

    dataModel.put(Keys.RESULTS, results);

    final long chargePointSum = pointtransferQueryService.getChargePointSum();
    final int pointExchangeUnit = Symphonys.getInt("pointExchangeUnit");
    dataModel.put(Common.CHARGE_SUM, chargePointSum / pointExchangeUnit);

    final JSONObject pagination = result.optJSONObject(Pagination.PAGINATION);
    final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT);
    final JSONArray pageNums = pagination.optJSONArray(Pagination.PAGINATION_PAGE_NUMS);
    dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.opt(0));
    dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.opt(pageNums.length() - 1));
    dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
    dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
    dataModel.put(Pagination.PAGINATION_PAGE_NUMS, CollectionUtils.jsonArrayToList(pageNums));

    filler.fillHeaderAndFooter(request, response, dataModel);
}
 
Example 20
@Override
public Set<FlowFile> readSequenceFile(Path file, Configuration configuration, FileSystem fileSystem) throws IOException {

    final SequenceFile.Reader reader;

    Set<FlowFile> flowFiles = new HashSet<>();
    reader = new SequenceFile.Reader(configuration, Reader.file(fileSystem.makeQualified(file)));
    final Text key = new Text();
    final KeyValueWriterCallback callback = new KeyValueWriterCallback(reader);
    final String inputfileName = file.getName() + "." + System.nanoTime() + ".";
    int counter = 0;
    LOG.debug("Read from SequenceFile: {} ", new Object[]{file});
    try {
        while (reader.next(key)) {
            String fileName = key.toString();
            // the key may be a file name, and may not
            if (LOOKS_LIKE_FILENAME.matcher(fileName).matches()) {
                if (fileName.contains(File.separator)) {
                    fileName = StringUtils.substringAfterLast(fileName, File.separator);
                }
                fileName = fileName + "." + System.nanoTime();
            } else {
                fileName = inputfileName + ++counter;
            }

            FlowFile flowFile = session.create();
            flowFile = session.putAttribute(flowFile, CoreAttributes.FILENAME.key(), fileName);
            callback.key = key;
            try {
                flowFile = session.write(flowFile, callback);
                flowFiles.add(flowFile);
            } catch (ProcessException e) {
                LOG.error("Could not write to flowfile {}", new Object[]{flowFile}, e);
                session.remove(flowFile);
            }
            key.clear();
        }
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return flowFiles;
}