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:org.pepstock.jem.ant.tasks.AntBatchSecurityManager.java

@Override
public void checkPermission(Permission perm) {
    // checks if someone add a security manager
    if (perm instanceof RuntimePermission && "setSecurityManager".equalsIgnoreCase(perm.getName())) {
        if (!isAllowedSetSecurityManager()) {
            LogAppl.getInstance().emit(NodeMessage.JEMC274E);
            throw new SecurityException(NodeMessage.JEMC274E.toMessage().getMessage());
        }/*from w w  w. ja v a 2 s .c  om*/
        return;
    }
    // this check is necessary to avoid that someone
    // set jem properties, accessing outside of GFS
    if (perm instanceof PropertyPermission && "write".equalsIgnoreCase(perm.getActions())
            && perm.getName().startsWith("jem")) {
        LogAppl.getInstance().emit(NodeMessage.JEMC127E);
        throw new SecurityException(NodeMessage.JEMC127E.toMessage().getMessage());
    }
    // checks is administrator. if true return.
    if (isAdministrator() || isInternalAction()) {
        return;
    }
    // checks the file access
    // calling the right method, in according
    // with the action of permission
    if (perm instanceof FilePermission) {
        if ("read".equalsIgnoreCase(perm.getActions())) {
            checkRead(perm.getName());
        } else if ("write".equalsIgnoreCase(perm.getActions())) {
            checkWrite(perm.getName());
        } else if ("delete".equalsIgnoreCase(perm.getActions())) {
            checkDelete(perm.getName());
        } else {
            checkRead(perm.getName());
        }
    } else if (perm instanceof SocketPermission) {
        // checks the RMI access.
        // checks to RMI is not allowed if you're not a admin
        SocketPermission sperm = (SocketPermission) perm;
        int port = Parser.parseInt(StringUtils.substringAfter(sperm.getName(), ":"), Integer.MAX_VALUE);
        int portRmi = Parser.parseInt(System.getProperty(RmiKeys.JEM_RMI_PORT), Integer.MIN_VALUE);
        // if is going to RMI port and
        // is not executing JEM code and is not grantor
        if (port == portRmi && !isInternalAction() && !isGrantor()) {
            // extracts host name
            String hostname = StringUtils.substringBefore(sperm.getName(), ":");
            try {
                // gets hostname and localhost
                String resolved = InetAddress.getByName(hostname).getHostAddress();
                String localhost = InetAddress.getLocalHost().getHostAddress();
                // if they are equals and the user
                // desn't have the internal service permission
                // EXCEPTION!!
                if (resolved.equalsIgnoreCase(localhost)
                        && !checkBatchPermission(Permissions.INTERNAL_SERVICES)) {
                    LogAppl.getInstance().emit(NodeMessage.JEMC128E);
                    throw new SecurityException(NodeMessage.JEMC128E.toMessage().getMessage());
                }
            } catch (UnknownHostException e) {
                // if there is an error on resolving the hostname
                LogAppl.getInstance().emit(NodeMessage.JEMC128E);
                throw new SecurityException(NodeMessage.JEMC128E.toMessage().getMessage(), e);
            }
        }
    }
}

From source file:org.pepstock.jem.jppf.JPPFUtil.java

/**
 * Parses address, port and load JPPF properties to connect to JPPF.
 * @param props JPPF properties to load/*www.ja v a2 s .c o  m*/
 * @param addressParm address to parse
 * @throws JPPFMessageException if address is not valid
 */
public static void loadTypedProperties(TypedProperties props, String addressParm) throws JPPFMessageException {
    // parses addresses (comma separated)
    String address = StringUtils.remove(addressParm, " ");
    String[] addresses = StringUtils.split(address, ",");
    if (addresses != null && addresses.length > 0) {
        // calculate JPPF.DRIVERS properties
        StringBuilder drivers = new StringBuilder();
        for (int i = 0; i < addresses.length; i++) {
            // parses address. FORMAT: [host|ipaddress]:[port]
            if (addresses[i].contains(":")) {
                String host = StringUtils.substringBefore(addresses[i], ":");
                String port = StringUtils.substringAfter(addresses[i], ":");

                // drivers is named with counter
                String driver = Keys.JEM_JPPF_DRIVER_PREFIX + i;

                props.setProperty(driver + Keys.JEM_JPPF_PORT_SUFFIX, port);
                props.setProperty(driver + Keys.JEM_JPPF_SERVER_SUFFIX, host);
                // drivers are defined blank separated
                drivers.append(driver).append(" ");
            } else {
                throw new JPPFMessageException(JPPFMessage.JEMJ008E, addresses[i]);
            }
        }
        // sets drivers
        props.setProperty(Keys.JEM_JPPF_DRIVERS, drivers.toString());
    }
}

From source file:org.pepstock.jem.node.https.SubmitHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    // extracts the host
    String host = context.getAttribute(JOB_SUBMIT_IP_ADDRESS_KEY).toString();
    // gets HTTP method (uses locale ENGLISH to be sure to have POST)
    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    // if NOT post, exception!
    if (!method.equals(POST)) {
        LogAppl.getInstance().emit(NodeMessage.JEMC284W, method, host);
        throw new MethodNotSupportedException(
                NodeMessage.JEMC284W.toMessage().getFormattedMessage(method, host));
    }/*from w  w  w  . j  a  v  a2 s .  c o m*/
    // gets the URI or the request
    String target = request.getRequestLine().getUri();
    // if is not the same , accepts, exception!
    if (!target.equalsIgnoreCase(DEFAULT_ACTION)) {
        LogAppl.getInstance().emit(NodeMessage.JEMC285W, target, host);
        throw new MethodNotSupportedException(
                NodeMessage.JEMC285W.toMessage().getFormattedMessage(target, host));
    }
    // checks the HTTP request
    if (request instanceof HttpEntityEnclosingRequest) {
        // gets the entity of the request
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        // gets the body in string format
        String result = EntityUtils.toString(entity, CharSet.DEFAULT);
        // reads the first line,
        // with all URL encoded variables  
        String vars = StringUtils.substringBefore(result, DELIMITER);
        // loads a map with all parms
        Map<String, String> parms = loadParametersMap(URLEncodedUtils.parse(vars, CharSet.DEFAULT));
        // gets the USER
        String user = parms.get(SubmitParameters.USER.getName());
        // if JEM is configured to have the Socket Interceptor on HC
        // the client MUST provide a SIGNATURE (using own private key) with
        // the user crypted inside
        if (Main.getHazelcastConfig().getNetworkConfig().getSocketInterceptorConfig().isEnabled()) {
            // checks if there is the signature
            if (parms.containsKey(USER_SIGNATURE_KEY)) {
                // gets the signature in HEX format
                String cryptedUserString = parms.get(USER_SIGNATURE_KEY);
                // gets keys stores
                KeyStoresInfo keyStoresInfo = KeyStoreUtil.getKeyStoresInfo();
                try {
                    // extracts from the USER key store the PUBLIC KEY (upload by UI) for the user  
                    PublicKey publicKey = KeysUtil.getPublicKeyByAlias(keyStoresInfo.getUserKeystoreInfo(),
                            user);
                    // creates tne SIGNATURE verifying steps
                    Signature signature = Signature.getInstance("SHA256withRSA");
                    // sets public key
                    signature.initVerify(publicKey);
                    // sets content to check. It uses USER
                    signature.update(user.getBytes(CharSet.DEFAULT_CHARSET_NAME));
                    // checks if is verified
                    if (!signature.verify(Hex.decodeHex(cryptedUserString.toCharArray()))) {
                        // if not, log and EXCEPTION
                        LogAppl.getInstance().emit(NodeMessage.JEMC286W, user, host);
                        throw new HttpException(
                                NodeMessage.JEMC286W.toMessage().getFormattedMessage(user, host));
                    }
                } catch (MessageException e) {
                    LogAppl.getInstance().emit(NodeMessage.JEMC286W, user, host);
                    throw new ProtocolException(e.getMessage(), e);
                } catch (KeyException e) {
                    throw new ProtocolException(e.getMessage(), e);
                } catch (DecoderException e) {
                    throw new ProtocolException(e.getMessage(), e);
                } catch (NoSuchAlgorithmException e) {
                    throw new ProtocolException(e.getMessage(), e);
                } catch (SignatureException e) {
                    throw new ProtocolException(e.getMessage(), e);
                }
            } else {
                LogAppl.getInstance().emit(NodeMessage.JEMC287W, user, host);
                // if here, the signature is missing
                throw new HttpException(NodeMessage.JEMC287W.toMessage().getFormattedMessage(user, host));
            }
        }
        // gets JEM environemnt name and its passwrod
        String env = parms.get(SubmitParameters.ENV.getName());
        String password = parms.get(SubmitParameters.PASSWORD.getName());
        // checks if password and env are same, 
        // comparing with the HC configuration
        if (!Main.getHazelcastConfig().getGroupConfig().getName().equalsIgnoreCase(env)
                || !Main.getHazelcastConfig().getGroupConfig().getPassword().equalsIgnoreCase(password)) {
            // if not equals, exception
            LogAppl.getInstance().emit(NodeMessage.JEMC288W, host);
            throw new HttpException(NodeMessage.JEMC288W.toMessage().getFormattedMessage(host));
        }

        // reads teh second row of the body, with the JCL
        String jcl = StringUtils.substringAfter(result, DELIMITER);

        // sets the entity to send back, submitting the job.
        // it returns the JOBID
        StringEntity resultEntity = new StringEntity(submit(jcl, user, host, parms),
                ContentType.create(RESPONSE_MIME_TYPE, CharSet.DEFAULT_CHARSET_NAME));
        // sets STATUS code and entity 
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(resultEntity);
    } else {
        // if here, the request is not correct
        LogAppl.getInstance().emit(NodeMessage.JEMC284W, method, host);
        throw new MethodNotSupportedException(
                NodeMessage.JEMC284W.toMessage().getFormattedMessage(method, host));
    }
}

From source file:org.pepstock.jem.node.system.GetJobSystemActivity.java

/**
 * Checks if job is the same of passed and returns system resources
 * consumption//from   w ww .  j a v  a 2s  .com
 * 
 * @return system activity object with all used resources by the job
 * @throws SigarException 
 * @throws Exception occurs if errors
 */
@Override
public JobSystemActivity call() throws SigarException {
    JobSystemActivity activity = new JobSystemActivity();

    // check if there's a job current in execution. If not, do nothing
    if (Main.CURRENT_TASKS.containsKey(job.getId())) {
        // Checks if the job, passed as parameter, is the same of current
        // node. If not, logs a warning

        // parse process id because the form is pid@hostname
        String pid = StringUtils.substringBefore(job.getProcessId(), "@");
        long longPid = Parser.parseLong(pid, -1L);

        // if pid is correct
        if (longPid != -1L) {
            // gets sigar clearing the cache
            Sigar sigar = new Sigar();
            SigarProxy proxyFirst = SigarProxyCache.newInstance(sigar, 0);

            // gets all processes
            OSProcess head = getProcessesTree(longPid, proxyFirst);
            // gets cpu
            long cpuFirst = getCpu(head);
            sigar.close();
            // clear SIGAR
            SigarProxyCache.clear(proxyFirst);
            // wait for another sample
            try {
                Thread.sleep(INTERVAL);
            } catch (InterruptedException e) {
                // ignore
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }

            // gets sigar clearing the cache
            sigar = new Sigar();
            SigarProxy proxyLast = SigarProxyCache.newInstance(sigar, 0);
            // gets new OSprocess
            head = getProcessesTree(longPid, proxyLast);
            // gets CPU
            long cpuLast = getCpu(head);

            // calculate consumed CPU
            long cpuUsed = cpuLast - cpuFirst;
            // gets possible using the processors amount
            long totPossibleCpu = INTERVAL
                    * ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();

            double cpuUsedPercent = cpuUsed * 1D / totPossibleCpu;
            cpuUsedPercent = Math.min(Math.max(cpuUsedPercent, 0D), 1D);
            activity.setCpu(cpuLast);
            activity.setCpuPerc(cpuUsedPercent);
            // gets MEMORY
            activity.setMemory(getMemory(head));
            activity.setActive(true);
            sigar.close();

            activity.setProcess(head);
        }
    }
    return activity;
}

From source file:org.pepstock.jem.node.tasks.JobTask.java

/**
 * Cancels the execution of job, canceling the created process.<br>
 * Uses the command of operating system to do it and the process id passed
 * by RMI from executed job./*from   w w  w. ja  va  2  s  . co  m*/
 * 
 * @see org.pepstock.jem.node.rmi.TasksDoorImpl#setJobStarted(String)
 * @param pid process id to cancel
 * @param force if true, use force attribute
 * @return true if it was able to cancel the job in execution otherwise
 *         false
 */
public final boolean cancel(String pid, boolean force) {
    // PID is usually pass in the format [pid]@[hostname] by JMX
    // implementation of JDK.

    String id = StringUtils.substringBefore(getJob().getProcessId(), "@");
    long intId = Parser.parseLong(id, -1L);
    if (intId == -1L) {
        return false;
    }

    try {
        String user = job.isUserSurrogated() ? job.getJcl().getUser() : job.getUser();
        AbstractFactory currFactory = (AbstractFactory) getFactory();
        boolean useSudo = currFactory.isUseSudo() && !user.equalsIgnoreCase(Main.getNode().getUser());
        isCancelled = true;
        isCancelled = CurrentPlatform.getInstance().kill(intId, user, force, useSudo);
    } catch (Exception e) {
        isCancelled = false;
        LogAppl.getInstance().emit(NodeMessage.JEMC017E, e);
    }
    return isCancelled;
}

From source file:org.pepstock.jem.springbatch.tasks.SpringBatchSecurityManager.java

@Override
public void checkPermission(Permission perm) {
    // checks if someone add a security manager
    if (perm instanceof RuntimePermission && "setSecurityManager".equalsIgnoreCase(perm.getName())) {
        LogAppl.getInstance().emit(NodeMessage.JEMC274E);
        throw new SecurityException(NodeMessage.JEMC274E.toMessage().getMessage());
    }//from w  w w.ja  v  a 2 s . c om
    // this check is necessary to avoid that someone
    // set jem properties, accessing outside of GFS
    if (perm instanceof PropertyPermission && "write".equalsIgnoreCase(perm.getActions())
            && perm.getName().startsWith("jem")) {
        LogAppl.getInstance().emit(NodeMessage.JEMC127E);
        throw new SecurityException(NodeMessage.JEMC127E.toMessage().getMessage());
    }
    // checks is administrator. if true return.
    if (isAdministrator() || isInternalAction()) {
        return;
    }
    // checks the file access
    // calling the right method, in according
    // with the action of permission
    if (perm instanceof FilePermission) {
        if ("read".equalsIgnoreCase(perm.getActions())) {
            checkRead(perm.getName());
        } else if ("write".equalsIgnoreCase(perm.getActions())) {
            checkWrite(perm.getName());
        } else if ("delete".equalsIgnoreCase(perm.getActions())) {
            checkDelete(perm.getName());
        } else {
            checkRead(perm.getName());
        }
    } else if (perm instanceof SocketPermission) {
        // checks the RMI access.
        // checks to RMI is not allowed if you're not a admin
        SocketPermission sperm = (SocketPermission) perm;
        int port = Parser.parseInt(StringUtils.substringAfter(sperm.getName(), ":"), Integer.MAX_VALUE);
        int portRmi = Parser.parseInt(System.getProperty(RmiKeys.JEM_RMI_PORT), Integer.MIN_VALUE);
        // if is going to RMI port and
        // is not executing JEM code and is not grantor
        if (port == portRmi && !isInternalAction() && !isGrantor()) {
            // extracts host name
            String hostname = StringUtils.substringBefore(sperm.getName(), ":");
            try {
                // gets hostname and localhost 
                String resolved = InetAddress.getByName(hostname).getHostAddress();
                String localhost = InetAddress.getLocalHost().getHostAddress();
                // if they are equals and the user
                // desn't have the internal service permission
                // EXCEPTION!!
                if (resolved.equalsIgnoreCase(localhost)
                        && !checkBatchPermission(Permissions.INTERNAL_SERVICES)) {
                    LogAppl.getInstance().emit(NodeMessage.JEMC128E);
                    throw new SecurityException(NodeMessage.JEMC128E.toMessage().getMessage());
                }
            } catch (UnknownHostException e) {
                // if there is an error on resolving the hostname
                LogAppl.getInstance().emit(NodeMessage.JEMC128E);
                throw new SecurityException(NodeMessage.JEMC128E.toMessage().getMessage(), e);
            }
        }
    }
}

From source file:org.phenotips.diagnosis.internal.DefaultDiagnosisService.java

@Override
public List<VocabularyTerm> getDiagnosis(List<String> phenotypes, List<String> nonstandardPhenotypes,
        int limit) {
    // TODO: use the `nonstandardPhenotypes` argument

    Observations o = new Observations();
    o.observations = new boolean[this.boqa.getOntology().getNumberOfTerms()];
    boolean searchIsEmpty = true;

    // Add all hpo terms with ancestors to array of booleans
    for (String hpo : phenotypes) {
        Term t = this.boqa.getOntology().getTerm(hpo);
        searchIsEmpty = !addTermAndAncestors(t, o) && searchIsEmpty;
    }//from   ww w.ja v  a2s .  c o m

    if (searchIsEmpty) {
        return Collections.emptyList();
    }

    // Get marginals
    final BOQA.Result res = this.boqa.assignMarginals(o, false, 1);

    // All of this is sorting diseases by marginals
    Integer[] order = new Integer[res.size()];
    for (int i = 0; i < order.length; i++) {
        order[i] = i;
    }

    Arrays.sort(order, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            if (res.getMarginal(o1) < res.getMarginal(o2)) {
                return 1;
            }
            if (res.getMarginal(o1) > res.getMarginal(o2)) {
                return -1;
            }
            return 0;
        }
    });

    // Get top limit results
    List<VocabularyTerm> results = new ArrayList<>();
    for (int id : order) {
        if (results.size() >= limit) {
            break;
        }

        String termId = String.valueOf(this.omimMap.get(id));
        String vocabularyId = StringUtils.substringBefore(termId, ":");

        // ignore non-OMIM diseases (BOQA has ORPHANET and DECIPHER as well)
        if (!"OMIM".equals(vocabularyId)) {
            continue;
        }

        // Strip 'O' in "OMIM"
        termId = termId.substring(1);

        VocabularyTerm term = this.vocabulary.resolveTerm(termId);

        if (term == null) {
            this.logger.warn(
                    String.format("Unable to resolve OMIM term '%s' due to outdated OMIM vocabulary.", termId));
            continue;
        }

        // Do not suggest diseases that start with *, +, and ^
        Pattern pattern = Pattern.compile("[*+^]");
        if (pattern.matcher(term.getName().substring(0, 1)).matches()) {
            continue;
        }

        results.add(term);

    }

    this.logger.debug(String.valueOf(results));

    return results;
}

From source file:org.phenotips.ontology.internal.DefaultOntologyManager.java

/**
 * Finds the owner ontology given a term identifier. The ontology is identified by the term ID prefix, for example
 * {@code HP} in {@code HP:0002066}.//  w  ww .jav a 2 s  . c o  m
 *
 * @param termId the term identifier to process
 * @return the owner ontology, or {@code null} if the term doesn't belong to a known ontology
 */
private OntologyService getOntologyForTerm(String termId) {
    String ontologyId = StringUtils.substringBefore(termId, ":");
    if (StringUtils.isNotBlank(ontologyId)) {
        return this.ontologies.get(ontologyId);
    }
    return null;
}

From source file:org.phenotips.ontology.internal.solr.LazySolrTermSet.java

/**
 * Constructor that provides the list of {@link #identifiers terms identifier} and the {@link #ontology owner
 * ontology}.//from   ww w  . j a v  a2s  . co m
 *
 * @param identifiers the {@link #identifiers identifiers to load}
 * @param ontology the {@link #ontology owner ontology}
 */
public LazySolrTermSet(Collection<Object> identifiers, OntologyService ontology) {
    if (identifiers == null || identifiers.isEmpty()) {
        this.identifiers = Collections.emptySet();
        this.terms = Collections.emptySet();
    } else {
        this.identifiers = new HashSet<String>(identifiers.size());
        for (Object id : identifiers) {
            this.identifiers.add(StringUtils.substringBefore(String.valueOf(id), " "));
        }
    }
    this.ontology = ontology;
}

From source file:org.phenotips.oo.OmimSourceParser.java

private void loadField(String name, String value) {
    if (StringUtils.isAnyBlank(name, value)) {
        return;//  w w w .ja v a 2s  .c  o  m
    }
    switch (name) {
    case FIELD_MIM_NUMBER:
        this.crtTerm.addField(ID_FIELD, value);
        break;
    case FIELD_TITLE:
        String title = StringUtils.substringBefore(value, TITLE_SEPARATOR).trim();
        String[] synonyms = StringUtils.split(StringUtils.substringAfter(value, TITLE_SEPARATOR),
                TITLE_SEPARATOR);
        this.crtTerm.addField(NAME_FIELD, title);
        for (String synonym : synonyms) {
            this.crtTerm.addField(SYNONYM_FIELD, synonym.trim());
        }
        break;
    case FIELD_TEXT:
        this.crtTerm.addField("def", value);
        break;
    default:
        return;
    }
}