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.dianping.lion.register.zookeeper.ConfigZookeeperService.java

public void set(String path, String value) throws Exception {
    if (value != null) {
        value = SecurityUtils.tryDecode(value);
        set(path, value.getBytes(charset));
    } else {//  w ww  .  j  av  a  2 s  . c  o m
        logger.warn("Set null config value to zk[" + StringUtils.substringBefore(this.serverIps, ",")
                + "] with path[" + path + "].");
    }
}

From source file:com.adobe.ac.pmd.engines.AbstractFlexPmdEngine.java

private String getReportType() {
    return StringUtils.substringBefore(StringUtils.substringAfter(getClass().getName(), "FlexPmd"), "Engine");
}

From source file:eionet.cr.util.URLUtil.java

/**
 * Connect to the URL and check if it exists at the remote end. Local identifiers are removed (the part after the '#') before
 * connecting. The method returns true (i.e. URL is considered as "not existing") if the given URL is malformed, or its
 * connection throws a {@link UnknownHostException} or sends a HTTP code that is 501 or 505 or anything in the range of 400
 * to 499. The latter range, however, is ignored if the given boolean input is is true (meaning a client error is OK).
 *
 * @param urlStr the URL to check./*from ww  w  .j  a  va2 s  .  c o m*/
 * @param clientErrorOk If true, then a response code in the range of 400 to 499 is considered OK.
 * @return As described above.
 */
public static boolean isNotExisting(String urlStr, boolean clientErrorOk) {

    int responseCode = -1;
    IOException ioe = null;
    URLConnection urlConnection = null;
    try {
        URL url = new URL(StringUtils.substringBefore(urlStr, "#"));
        urlConnection = escapeIRI(url).openConnection();
        urlConnection.setRequestProperty("Connection", "close");
        responseCode = ((HttpURLConnection) urlConnection).getResponseCode();
    } catch (IOException e) {
        ioe = e;
    } finally {
        URLUtil.disconnect(urlConnection);
    }

    return ioe instanceof MalformedURLException || ioe instanceof UnknownHostException
            || (!clientErrorOk && isClientError(responseCode))
            || responseCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED
            || responseCode == HttpURLConnection.HTTP_VERSION;
}

From source file:com.szl.common.utils.Struts2Utils.java

/**
 * ?contentTypeheaders.//from ww  w  .  ja  v  a 2s.co  m
 */
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) {
        ServletUtils.setNoCacheHeader(response);
    }

    return response;
}

From source file:eionet.cr.staging.FileDownloader.java

/**
 * Derives a name for the file to be downloaded from the given {@link URLConnection}.
 *
 * @param connection The given {@link URLConnection}.
 * @return The derived file name./*from  ww  w  . j  a  v a2s  . co  m*/
 */
private String getFileName(URLConnection connection) {

    // If file name already given, just return it.
    if (StringUtils.isNotBlank(newFileName)) {
        return newFileName;
    }

    // Attempt detection from the response's "Content-Disposition" header.
    String contentDisposition = connection.getHeaderField("Content-Disposition");
    if (StringUtils.isNotBlank(contentDisposition)) {
        String s = StringUtils.substringAfter(contentDisposition, "filename");
        if (StringUtils.isNotBlank(s)) {
            s = StringUtils.substringAfter(s, "=");
            if (StringUtils.isNotBlank(s)) {
                s = StringUtils.substringAfter(s, "\"");
                if (StringUtils.isNotBlank(s)) {
                    s = StringUtils.substringBefore(s, "\"");
                    if (StringUtils.isNotBlank(s)) {
                        return s.trim();
                    }
                }
            }
        }
    }

    // // Attempt detection from the response's "Content-Location" header.
    // String contentLocation = connection.getHeaderField("Content-Location");
    // if (StringUtils.isNotBlank(contentLocation)) {
    // String s = new File(contentLocation).getName();
    // if (StringUtils.isNotBlank(s)) {
    // return s.trim();
    // }
    // }
    //
    // Attempt detection from the URL itself.

    String s = StringUtils.substringAfterLast(connection.getURL().toString(), "#");
    if (StringUtils.isBlank(s)) {
        s = StringUtils.substringAfterLast(connection.getURL().toString(), "/");
    }

    if (StringUtils.isNotBlank(s)) {
        // Remove all characters that are not one of these: a latin letter, a digit, a minus, a dot, an underscore.
        s = s.replaceAll("[^a-zA-Z0-9-._]+", "");
    }

    // If still no success, then just generate a hash from the URL.
    return StringUtils.isBlank(s) ? DigestUtils.md5Hex(connection.getURL().toString()) : s;
}

From source file:info.magnolia.cms.module.ModuleUtil.java

public static void bootstrap(String[] resourceNames) throws IOException, RegisterException {

    HierarchyManager hm = MgnlContext.getHierarchyManager(ContentRepository.CONFIG);

    // sort by length --> import parent node first
    List list = new ArrayList(Arrays.asList(resourceNames));

    Collections.sort(list, new Comparator() {

        public int compare(Object name1, Object name2) {
            return ((String) name1).length() - ((String) name2).length();
        }//www.  j  av  a  2s . com
    });

    for (Iterator iter = list.iterator(); iter.hasNext();) {
        String resourceName = (String) iter.next();

        // windows again
        resourceName = StringUtils.replace(resourceName, "\\", "/");

        String name = StringUtils.removeEnd(StringUtils.substringAfterLast(resourceName, "/"), ".xml");

        String repository = StringUtils.substringBefore(name, ".");
        String pathName = StringUtils.substringAfter(StringUtils.substringBeforeLast(name, "."), "."); //$NON-NLS-1$
        String nodeName = StringUtils.substringAfterLast(name, ".");
        String fullPath;
        if (StringUtils.isEmpty(pathName)) {
            pathName = "/";
            fullPath = "/" + nodeName;
        } else {
            pathName = "/" + StringUtils.replace(pathName, ".", "/");
            fullPath = pathName + "/" + nodeName;
        }

        // if the path already exists --> delete it
        try {
            if (hm.isExist(fullPath)) {
                hm.delete(fullPath);
                if (log.isDebugEnabled())
                    log.debug("already existing node [{}] deleted", fullPath);
            }

            // if the parent path not exists just create it
            if (!pathName.equals("/")) {
                ContentUtil.createPath(hm, pathName, ItemType.CONTENT);
            }
        } catch (Exception e) {
            throw new RegisterException("can't register bootstrap file: [" + name + "]", e);
        }
        InputStream stream = ModuleUtil.class.getResourceAsStream(resourceName);
        DataTransporter.executeImport(pathName, repository, stream, name, false,
                ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING, true, true);
    }
}

From source file:com.sa.npopa.samples.hbase.RowCounter.java

/**
 * Sets up the actual job.//  w w w  .  j  a va2s.  c  o  m
 *
 * @param conf  The current configuration.
 * @param args  The command line parameters.
 * @return The newly created job.
 * @throws IOException When setting up the job fails.
 */
public static Job createSubmittableJob(Configuration conf, String[] args) throws IOException {
    String tableName = args[0];
    String startKey = null;
    String endKey = null;
    long startTime = 0;
    long endTime = 0;

    StringBuilder sb = new StringBuilder();

    final String rangeSwitch = "--range=";
    final String startTimeArgKey = "--starttime=";
    final String endTimeArgKey = "--endtime=";
    final String expectedCountArg = "--expected-count=";

    // First argument is table name, starting from second
    for (int i = 1; i < args.length; i++) {
        if (args[i].startsWith(rangeSwitch)) {
            String[] startEnd = args[i].substring(rangeSwitch.length()).split(",", 2);
            if (startEnd.length != 2 || startEnd[1].contains(",")) {
                printUsage("Please specify range in such format as \"--range=a,b\" "
                        + "or, with only one boundary, \"--range=,b\" or \"--range=a,\"");
                return null;
            }
            startKey = startEnd[0];
            endKey = startEnd[1];
            continue;
        }
        if (args[i].startsWith(startTimeArgKey)) {
            startTime = Long.parseLong(args[i].substring(startTimeArgKey.length()));
            continue;
        }
        if (args[i].startsWith(endTimeArgKey)) {
            endTime = Long.parseLong(args[i].substring(endTimeArgKey.length()));
            continue;
        }
        if (args[i].startsWith(expectedCountArg)) {
            conf.setLong(EXPECTED_COUNT_KEY, Long.parseLong(args[i].substring(expectedCountArg.length())));
            continue;
        }
        // if no switch, assume column names
        sb.append(args[i]);
        sb.append(" ");
    }
    if (endTime < startTime) {
        printUsage("--endtime=" + endTime + " needs to be greater than --starttime=" + startTime);
        return null;
    }

    Job job = Job.getInstance(conf, conf.get(JOB_NAME_CONF_KEY, NAME + "_" + tableName));
    job.setJarByClass(RowCounter.class);
    Scan scan = new Scan();
    scan.setCacheBlocks(false);
    if (startKey != null && !startKey.equals("")) {
        scan.setStartRow(Bytes.toBytes(startKey));
    }
    if (endKey != null && !endKey.equals("")) {
        scan.setStopRow(Bytes.toBytes(endKey));
    }
    if (sb.length() > 0) {
        for (String columnName : sb.toString().trim().split(" ")) {
            String family = StringUtils.substringBefore(columnName, ":");
            String qualifier = StringUtils.substringAfter(columnName, ":");

            if (StringUtils.isBlank(qualifier)) {
                scan.addFamily(Bytes.toBytes(family));
            } else {
                scan.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
            }
        }
    }
    scan.setFilter(new FirstKeyOnlyFilter());
    scan.setTimeRange(startTime, endTime == 0 ? HConstants.LATEST_TIMESTAMP : endTime);
    job.setOutputFormatClass(NullOutputFormat.class);
    TableMapReduceUtil.initTableMapperJob(tableName, scan, RowCounterMapper.class, ImmutableBytesWritable.class,
            Result.class, job);
    job.setNumReduceTasks(0);
    return job;
}

From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java

/**
 * Returns the {@link Method} defined in {@link Class}. This method can have any visibility, i.e. we can
 * find even protected/private methods. Can return <code>null</code> if no method with given signature
 * found.//from  www  .j a  va2s.c  o  m
 * 
 * @param clazz
 *            the {@link Class} to get method from it, or its superclass.
 * @param signature
 *            the signature of method in same format as {@link #getMethodSignature(Method)}.
 * 
 * @return the {@link Method} for given signature, or <code>null</code> if no such method found.
 */
public static Method getMethodBySignature(Class<?> clazz, String signature) {
    Assert.isNotNull(clazz);
    Assert.isNotNull(signature);
    // extract name of method to perform fast check only by name, full signature requires too much time
    String signatureName = StringUtils.substringBefore(signature, "(");
    // check methods of given class and its super classes
    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
        Method method = getMethodBySignature0(c, signatureName, signature);
        if (method != null) {
            return method;
        }
    }
    // check methods of implemented interfaces
    for (Class<?> interfaceClass : clazz.getInterfaces()) {
        Method method = getMethodBySignature0(interfaceClass, signatureName, signature);
        if (method != null) {
            return method;
        }
    }
    // not found
    return null;
}

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/i18n</code>.
 *///from w w  w  . j  av  a2s  .  com
public static String getFullpathFromResource(final String resourcePath) {
    String resourceName = StringUtils.replace(resourcePath, "\\", "/");

    String name = getFilenameFromResource(resourceName, ".xml");
    String fullPath = DataTransporter.revertExportPath(name);
    String repository = StringUtils.substringBefore(fullPath, "/");

    return StringUtils.removeStart(fullPath, repository);
}

From source file:com.doculibre.constellio.services.StatusServicesImpl.java

@Override
public String getSizeOnDisk(RecordCollection collection) {
    if (collection != null) {
        String collectionName = collection.getName();
        String realCollectionName;
        if (SolrServicesImpl.isAliasInCloud(collectionName)) {
            realCollectionName = SolrServicesImpl.getRealCollectionInCloud(collectionName);
        } else {/*from  w  ww.j a  va  2s  . com*/
            realCollectionName = collectionName;
        }
        ModifiableSolrParams params = new ModifiableSolrParams();
        params.set(CommonParams.QT, "/replication");
        params.set("command", "details");

        try {
            StringBuffer formattedSize = new StringBuffer();
            CloudSolrServer cloudSolrServer = (CloudSolrServer) SolrCoreContext.getMainSolrServer();
            ClusterState clusterState = cloudSolrServer.getZkStateReader().getClusterState();
            Collection<Slice> slices = clusterState.getActiveSlices(realCollectionName);
            if (slices != null) {
                for (Slice slice : slices) {
                    Replica replica = clusterState.getLeader(realCollectionName, slice.getName());
                    HttpSolrServer solrServer = new HttpSolrServer(
                            "http://" + StringUtils.substringBefore(replica.getNodeName(), "_") + "/solr/"
                                    + collectionName);
                    QueryResponse response = solrServer.query(params);
                    formattedSize
                            .append(((NamedList) response.getResponse().get("details")).get("indexSize") + ",");
                }
                return formattedSize.toString();
            } else {
                return FileSizeUtils.formatSize(0, 2);
            }
        } catch (SolrServerException e) {
            return FileSizeUtils.formatSize(0, 2);
        }
    } else {
        return FileSizeUtils.formatSize(0, 2);
    }
}