Example usage for java.lang String subSequence

List of usage examples for java.lang String subSequence

Introduction

In this page you can find the example usage for java.lang String subSequence.

Prototype

public CharSequence subSequence(int beginIndex, int endIndex) 

Source Link

Document

Returns a character sequence that is a subsequence of this sequence.

Usage

From source file:com.swg.parse.docx.NewExtract.java

private String displayCleanUp(String value, String ValType) {

    if (value.contains("0  n/a") && ValType.contains("text field")) {
        value = value.replace("0  n/a", "");
    }// w  w  w  . j  ava 2 s. c  o m
    if (value.contains("1  n/a") && ValType.contains("text field")) {
        value = value.replace("1  n/a", "");
    }
    String valueTok[] = value.split("\\s+");
    StringBuilder builder = new StringBuilder();
    for (String str : valueTok) {
        builder.append(str).append(" ");
    }
    value = builder.toString();
    if (value.contains("section") && value.length() > value.indexOf("section") + "section".length() + 2) {
        value = value.replace(
                value.subSequence(value.indexOf("section"), value.indexOf("section") + "section".length() + 2),
                "");
    }
    return value;
}

From source file:com.odo.kcl.mobileminer.ProcSocketSet.java

/**
 * Search in /proc/<pid>/net for open network sockets.
 * http://www.tldp.org/LDP/Linux-Filesystem-Hierarchy/html/proc.html
 * http://www.onlamp.com/pub/a/linux/2000/11/16/LinuxAdmin.html
 *///from   w  w  w  .  j a  v  a  2 s  .  c  o m

//    /proc/<pid>/net/tcp example:
//  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
//    0: 00000000:445C 00000000:0000 0A 00000000:00000000 00:00000000 00000000  1000        0 15353 1 0000000000000000 100 0 0 10 0
//    1: 00000000:01BD 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 12341 1 0000000000000000 100 0 0 10 0
//    ...
//    12: 4F01A8C0:E1D0 B422C2AD:0050 01 00000000:00000000 02:000003A3 00000000  1000        0 154153 2 0000000000000000 23 4 28 10 -1
//  13: 0100007F:13AD 0100007F:B3B6 01 00000000:00000000 00:00000000 00000000  1000        0 34682 1 0000000000000000 20 4 1 10 -1
public void scan() {
    List<ActivityManager.RunningAppProcessInfo> procs = am.getRunningAppProcesses();
    Integer j, digitCount, digitInc;
    ArrayList<String> pids = new ArrayList<String>(); // Process IDs.
    ArrayList<String> names = new ArrayList<String>(); // Process names.
    ArrayList<String> uids = new ArrayList<String>(); // User IDs.
    HashMap<String, String> namesByUid = new HashMap<String, String>();
    HashMap<String, String> namesByPid = new HashMap<String, String>();
    HashMap<String, String> pidsByUid = new HashMap<String, String>();
    HashMap<String, String> pidsByName = new HashMap<String, String>();
    String thisUid, thisPid, thisName;

    BufferedReader reader;
    boolean ipv6 = false;

    String line;
    String[] tokens, remote;
    String remoteAddr, remoteIP, remotePort;
    HashMap<String, ArrayList<String>> discoveredSockets;
    ArrayList<Integer> remoteIPchunks;

    updated = false;

    // Populate the HashmMaps and create the process objects.
    for (ActivityManager.RunningAppProcessInfo p : procs) {
        thisPid = Integer.toString(p.pid);
        pids.add(thisPid);
        names.add(p.processName);
        namesByPid.put(thisPid, p.processName);
        thisUid = Integer.toString(p.uid);
        uids.add(thisUid);
        namesByUid.put(thisUid, p.processName);
        pidsByUid.put(thisUid, thisPid);
        pidsByName.put(p.processName, thisPid);

        if (processes.get(p.processName) == null)
            processes.put(p.processName, new Process(p.processName, thisPid));
    }

    // Purge any processes that have stopped.
    for (String name : processes.keySet()) {
        if (!names.contains(name)) {
            processes.get(name).closeAll();
        }
    }

    for (String prot : protocols) {
        if (ipv6) { // How many HEX digits specify each chunk of an ip address?
            digitCount = 4;
            digitInc = 3;
        } else {
            digitCount = 2;
            digitInc = 1;
        }
        ipv6 = !ipv6; // Protocols array alternates between ipv4 and ipv6.

        discoveredSockets = new HashMap<String, ArrayList<String>>();

        for (String scannedPid : pids) { // For each process ID...

            try {
                line = null;
                // Are we allowed to read /proc/<pid>/net/<protocol> ?
                reader = new BufferedReader(new FileReader("/proc/" + scannedPid + "/net/" + prot));

                while ((line = reader.readLine()) != null) {
                    tokens = line.split("\\s+"); // Split on whitespace...
                    remote = tokens[3].split(":"); // Maybe the fourth token is the remote address...
                    remoteAddr = remote[0];

                    if (remote.length > 1) { // ...if there are two tokens seperated by a ":".
                        thisUid = tokens[8];
                        thisPid = pidsByUid.get(thisUid);
                        thisName = namesByUid.get(thisUid);

                        if (thisName != null && thisPid != null) {
                            remotePort = Integer.valueOf(remote[1], 16).toString(); // Get the port from the HEX string.
                            remoteIPchunks = new ArrayList<Integer>();

                            for (j = 0; j < remoteAddr.length(); j += digitCount) { // Get each part of the ip address as a string...
                                remoteIPchunks.add(Integer
                                        .valueOf(remoteAddr.subSequence(j, j + digitInc).toString(), 16));
                            }

                            if (remoteIPchunks.get(0) != 0) {
                                remoteIP = TextUtils.join(".", remoteIPchunks); // ...then assemble it and add the socket.
                                if (discoveredSockets.get(thisName) == null)
                                    discoveredSockets.put(thisName, new ArrayList<String>());
                                discoveredSockets.get(thisName).add(remoteIP + ":" + remotePort);
                            }
                        }
                    }
                }

                for (String name : names) { // See which of the old sockets are still open.
                    if (processes.get(name) != null) {
                        if (discoveredSockets.get(name) != null) { // Do we need to broadcast any changes?
                            updated |= processes.get(name).checkSockets(prot, discoveredSockets.get(name));
                            for (String addr : discoveredSockets.get(name))
                                updated |= addSocket(prot, pidsByName.get(name), name, addr);
                        } else {
                            processes.get(name).closeAll(prot);
                        }
                    }
                }
            } catch (IOException e) {
                //Log.i("MinerService","Can't open /proc/<pid>/net");
            }
        }
    }

    if (updated)
        broadcast();
}

From source file:es.bsc.servicess.ide.editors.ImplementationFormPage.java

/**
 * Modify parameter element/* w  w w  . ja  v a 2  s .co m*/
 * @param serviceClass Orchestration class name
 * @param methodName Element method name
 * @param p Parameter
 * @throws PartInitException
 * @throws JavaModelException
 * @throws MalformedTreeException
 * @throws BadLocationException
 * @throws SAXException
 * @throws IOException
 * @throws ParserConfigurationException
 */
private void modifyDirection(String serviceClass, String methodName, CoreElementParameter p)
        throws PartInitException, JavaModelException, MalformedTreeException, BadLocationException,
        SAXException, IOException, ParserConfigurationException {
    log.debug("Modifying direction for core element" + serviceClass + "." + methodName + " parameter "
            + p.getName() + "(" + p.getDirection() + ")");
    ICompilationUnit cu = getCEInterface(serviceClass, ((ServiceFormEditor) getEditor()).getProject(),
            ((ServiceFormEditor) getEditor()).getProjectMetadata());
    if (cu != null) {
        Document document = new Document(cu.getSource());
        log.debug(document.get());
        String localtypeName = serviceClass.subSequence(serviceClass.lastIndexOf(".") + 1,
                serviceClass.length()) + "Itf";
        ASTParser parser = ASTParser.newParser(AST.JLS3); // handles JDK
        // 1.0, 1.1,
        // 1.2, 1.3,
        // 1.4, 1.5, 1.6
        parser.setSource(cu);
        CompilationUnit result = (CompilationUnit) parser.createAST(null);
        if (result != null) {
            result.recordModifications();
            log.debug(result.toString());
            AST ast = result.getAST();
            java.util.List<AbstractTypeDeclaration> types = result.types();
            log.debug("pack: " + result.getPackage().toString() + " types: " + result.types().size());
            if (result.types().size() > 0) {
                boolean find = false;
                for (AbstractTypeDeclaration type : types) {
                    log.debug("Type: " + type.getName().getIdentifier() + "("
                            + type.getName().getFullyQualifiedName() + ")");
                    if (type.getName().getIdentifier().equals(localtypeName)) {
                        MethodDeclaration[] methods = ((TypeDeclaration) type).getMethods();
                        for (MethodDeclaration m : methods) {
                            log.debug("method FQDN: " + m.getName().getFullyQualifiedName() + " identifier: "
                                    + m.getName().getIdentifier());
                            if (m.getName().getIdentifier().equals(methodName)) {
                                java.util.List<SingleVariableDeclaration> pars = m.parameters();
                                for (SingleVariableDeclaration var : pars) {
                                    log.debug("var FQDN: " + var.getName().getFullyQualifiedName()
                                            + " identifier: " + var.getName().getIdentifier());
                                    if (var.getName().getIdentifier().equals(p.getName())) {
                                        java.util.List<IExtendedModifier> mods = var.modifiers();
                                        for (IExtendedModifier mod : mods) {
                                            log.debug("modifier: " + mod.getClass().toString());
                                            if (mod.isAnnotation()) {
                                                if (((Annotation) mod).isNormalAnnotation()) {
                                                    log.debug("annotation: " + ((NormalAnnotation) mod)
                                                            .getTypeName().toString());
                                                    if (((NormalAnnotation) mod).getTypeName().toString()
                                                            .equals("Parameter")) {
                                                        java.util.List<MemberValuePair> vals = ((NormalAnnotation) mod)
                                                                .values();
                                                        MemberValuePair dir_value = null;
                                                        for (MemberValuePair v : vals) {
                                                            log.debug("member: " + v.getName().getIdentifier());
                                                            if (v.getName().getIdentifier()
                                                                    .equals("direction")) {
                                                                dir_value = v;
                                                                break;
                                                            }
                                                        }

                                                        if (dir_value == null) {
                                                            dir_value = ast.newMemberValuePair();
                                                            dir_value.setName(ast.newSimpleName("direction"));
                                                            QualifiedName qn = ast.newQualifiedName(
                                                                    ast.newSimpleName("Direction"),
                                                                    ast.newSimpleName(p.getDirection()));
                                                            dir_value.setValue(qn);
                                                            log.debug("Adding property to annotation: "
                                                                    + dir_value.toString());
                                                            vals.add(dir_value);
                                                        } else {
                                                            QualifiedName ex = (QualifiedName) dir_value
                                                                    .getValue();
                                                            log.debug("ValueClass: " + ex.getClass());
                                                            ex.setName(ast.newSimpleName(p.getDirection()));
                                                            log.debug("Changing direction: "
                                                                    + dir_value.toString());
                                                        }
                                                        find = true;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        if (find)
                                            break;
                                    }
                                }
                                if (find)
                                    break;
                            }
                        }
                        if (find)
                            break;
                    }
                }
                if (find) {
                    TextEdit edits = result.rewrite(document, cu.getJavaProject().getOptions(true));
                    edits.apply(document);
                    String newSource = document.get();
                    cu.getBuffer().setContents(newSource);
                    cu.save(null, true);
                    log.debug("writting modifications " + newSource);
                } else {
                    log.warn("Varaible and annotation not found");
                }

            } else {
                log.warn("No types found in the Compilation unit from AST");
            }
        } else {
            log.error("Error parsing Compilation unit with AST");
        }
    } else {
        log.error("Error getting Interface Compilation Unit");
    }
}

From source file:org.deeplearning4j.nn.graph.ComputationGraph.java

/**
 * String detailing the architecture of the computation graph.
 * Vertices are printed in a topological sort order.
 * Columns are Vertex Names with layer/vertex type, nIn, nOut, Total number of parameters and the Shapes of the parameters
 * And the inputs to the vertex//  ww w.  ja v  a  2 s .  c o  m
 * Will also give information about frozen layers/vertices, if any.
 * @return Summary as a string
 */
public String summary() {
    String ret = "\n";
    ret += StringUtils.repeat("=", 140);
    ret += "\n";
    ret += String.format("%-40s%-15s%-15s%-30s %s\n", "VertexName (VertexType)", "nIn,nOut", "TotalParams",
            "ParamsShape", "Vertex Inputs");
    ret += StringUtils.repeat("=", 140);
    ret += "\n";
    int frozenParams = 0;
    for (int currVertexIdx : topologicalOrder) {
        GraphVertex current = vertices[currVertexIdx];

        String name = current.getVertexName();
        String[] classNameArr = current.getClass().toString().split("\\.");
        String className = classNameArr[classNameArr.length - 1];

        String connections = "-";
        if (!current.isInputVertex()) {
            connections = configuration.getVertexInputs().get(name).toString();
        }
        String paramCount = "-";
        String in = "-";
        String out = "-";
        String paramShape = "-";
        if (current.hasLayer()) {
            Layer currentLayer = ((LayerVertex) current).getLayer();
            classNameArr = currentLayer.getClass().getName().split("\\.");
            className = classNameArr[classNameArr.length - 1];
            paramCount = String.valueOf(currentLayer.numParams());
            if (currentLayer.numParams() > 0) {
                paramShape = "";
                in = String.valueOf(((FeedForwardLayer) currentLayer.conf().getLayer()).getNIn());
                out = String.valueOf(((FeedForwardLayer) currentLayer.conf().getLayer()).getNOut());
                Set<String> paraNames = currentLayer.conf().getLearningRateByParam().keySet();
                for (String aP : paraNames) {
                    String paramS = ArrayUtils.toString(currentLayer.paramTable().get(aP).shape());
                    paramShape += aP + ":" + paramS + ", ";
                }
                paramShape = paramShape.subSequence(0, paramShape.lastIndexOf(",")).toString();
            }
            if (currentLayer instanceof FrozenLayer) {
                frozenParams += currentLayer.numParams();
                classNameArr = ((FrozenLayer) currentLayer).getInsideLayer().getClass().getName().split("\\.");
                className = "Frozen " + classNameArr[classNameArr.length - 1];
            }
        }
        ret += String.format("%-40s%-15s%-15s%-30s %s", name + " (" + className + ")", in + "," + out,
                paramCount, paramShape, connections);
        ret += "\n";
    }
    ret += StringUtils.repeat("-", 140);
    ret += String.format("\n%30s %d", "Total Parameters: ", params().length());
    ret += String.format("\n%30s %d", "Trainable Parameters: ", params().length() - frozenParams);
    ret += String.format("\n%30s %d", "Frozen Parameters: ", frozenParams);
    ret += "\n";
    ret += StringUtils.repeat("=", 140);
    ret += "\n";

    return ret;
}

From source file:org.deeplearning4j.nn.multilayer.MultiLayerNetwork.java

/**
 * String detailing the architecture of the multilayernetwork.
 * Columns are LayerIndex with layer type, nIn, nOut, Total number of parameters and the Shapes of the parameters
 * Will also give information about frozen layers, if any.
 * @return Summary as a string//  www.j  av a2s. c o  m
 */
public String summary() {
    String ret = "\n";
    ret += StringUtils.repeat("=", 140);
    ret += "\n";
    ret += String.format("%-40s%-15s%-15s%-30s\n", "LayerName (LayerType)", "nIn,nOut", "TotalParams",
            "ParamsShape");
    ret += StringUtils.repeat("=", 140);
    ret += "\n";
    int frozenParams = 0;
    for (Layer currentLayer : layers) {
        String name = String.valueOf(currentLayer.getIndex());
        String paramShape = "-";
        String in = "-";
        String out = "-";
        String[] classNameArr = currentLayer.getClass().getName().split("\\.");
        String className = classNameArr[classNameArr.length - 1];
        String paramCount = String.valueOf(currentLayer.numParams());
        if (currentLayer.numParams() > 0) {
            paramShape = "";
            in = String.valueOf(((FeedForwardLayer) currentLayer.conf().getLayer()).getNIn());
            out = String.valueOf(((FeedForwardLayer) currentLayer.conf().getLayer()).getNOut());
            Set<String> paraNames = currentLayer.conf().getLearningRateByParam().keySet();
            for (String aP : paraNames) {
                String paramS = ArrayUtils.toString(currentLayer.paramTable().get(aP).shape());
                paramShape += aP + ":" + paramS + ", ";
            }
            paramShape = paramShape.subSequence(0, paramShape.lastIndexOf(",")).toString();
        }
        if (currentLayer instanceof FrozenLayer) {
            frozenParams += currentLayer.numParams();
            classNameArr = ((FrozenLayer) currentLayer).getInsideLayer().getClass().getName().split("\\.");
            className = "Frozen " + classNameArr[classNameArr.length - 1];
        }
        ret += String.format("%-40s%-15s%-15s%-30s", name + " (" + className + ")", in + "," + out, paramCount,
                paramShape);
        ret += "\n";
    }
    ret += StringUtils.repeat("-", 140);
    ret += String.format("\n%30s %d", "Total Parameters: ", params().length());
    ret += String.format("\n%30s %d", "Trainable Parameters: ", params().length() - frozenParams);
    ret += String.format("\n%30s %d", "Frozen Parameters: ", frozenParams);
    ret += "\n";
    ret += StringUtils.repeat("=", 140);
    ret += "\n";
    return ret;
}

From source file:it.geosolutions.geoserver.rest.GeoServerRESTPublisher.java

/**
 * /*from   w w  w  .java2 s.c o m*/
 * /workspaces/<ws>/datastores/<ds>.xml /workspaces/<ws>/coveragestores/<ds>.xml
 * 
 * @param workspace
 * @param storeName
 * @param mosaicDir
 * @return true if successfully reloaded
 * @throws FileNotFoundException
 * @throws IllegalArgumentException
 * @throws MalformedURLException
 */
public boolean reloadStore(String workspace, final String storeName, StoreType storeType)
        throws IllegalArgumentException, MalformedURLException {
    final String url = HTTPUtils.append(this.restURL, "/rest/workspaces/", workspace, "/", storeType.toString(),
            "/", storeName, ".xml").toString();
    final String store = HTTPUtils.get(url, this.gsuser, this.gspass);

    if (store != null) {
        String storeTag = storeType.getTypeName();
        // switch (storeType) {
        // case COVERAGESTORES:
        // storeTag = storeType.toString().replaceAll("store", "");
        // break;
        // case DATASTORES:
        // storeTag = "featureTypes";
        // break;
        // default:
        // throw new IllegalArgumentException("Unrecognized type");
        // }

        String startTag = "<" + storeTag + ">";
        int start = store.indexOf(startTag);
        String endTag = "</" + storeTag + ">";
        int stop = store.indexOf(endTag) + endTag.length();
        return HTTPUtils.putXml(url, store.subSequence(0, start) + store.substring(stop), this.gsuser,
                this.gspass) != null ? true : false;
    } else
        return false;
}

From source file:org.kuali.kfs.gl.service.impl.PreScrubberServiceImpl.java

public PreScrubberReportData preprocessOriginEntries(Iterator<String> inputOriginEntries, String outputFileName)
        throws IOException {
    PrintStream outputStream = new PrintStream(outputFileName);

    Map<String, String> chartCodeCache = new LinkedHashMap<String, String>() {
        @Override/*from ww w . ja va  2  s . c o m*/
        protected boolean removeEldestEntry(Entry<String, String> eldest) {
            return size() > getMaxCacheSize();
        }
    };

    Set<String> nonExistentAccountCache = new TreeSet<String>();
    Set<String> multipleAccountCache = new TreeSet<String>();

    AccountService accountService = SpringContext.getBean(AccountService.class);
    ParameterService parameterService = SpringContext.getBean(ParameterService.class);
    boolean fillInChartCodesIfSpaces = deriveChartOfAccountsCodeIfSpaces();

    int inputLines = 0;
    int outputLines = 0;

    try {
        while (inputOriginEntries.hasNext()) {
            inputLines++;

            String originEntry = inputOriginEntries.next();
            String outputLine = originEntry;
            if (fillInChartCodesIfSpaces && originEntry.length() >= getExclusiveAccountNumberEndPosition()) {
                String chartOfAccountsCode = originEntry.substring(
                        getInclusiveChartOfAccountsCodeStartPosition(),
                        getExclusiveChartOfAccountsCodeEndPosition());
                if (GeneralLedgerConstants.getSpaceChartOfAccountsCode().equals(chartOfAccountsCode)) {
                    // blank chart code... try to find the chart code
                    String accountNumber = originEntry.substring(getInclusiveAccountNumberStartPosition(),
                            getExclusiveAccountNumberEndPosition());
                    if (StringUtils.isNotEmpty(accountNumber)) {
                        String replacementChartOfAccountsCode = null;
                        boolean nonExistent = false;
                        boolean multipleFound = false;

                        if (chartCodeCache.containsKey(accountNumber))
                            replacementChartOfAccountsCode = chartCodeCache.get(accountNumber);
                        else if (nonExistentAccountCache.contains(accountNumber))
                            nonExistent = true;
                        else if (multipleAccountCache.contains(accountNumber))
                            multipleFound = true;
                        else {
                            Collection<Account> results = accountService
                                    .getAccountsForAccountNumber(accountNumber);

                            if (results.isEmpty()) {
                                nonExistent = true;
                                nonExistentAccountCache.add(accountNumber);
                                LOG.warn("Could not find account record for account number " + accountNumber);
                            } else {
                                Iterator<Account> accounts = results.iterator();
                                Account account = accounts.next();
                                if (accounts.hasNext()) {
                                    LOG.warn("Multiple chart codes found for account number " + accountNumber
                                            + ", not filling in chart code for this account");
                                    TransactionalServiceUtils.exhaustIterator(accounts);
                                    multipleAccountCache.add(accountNumber);
                                    multipleFound = true;
                                } else {
                                    replacementChartOfAccountsCode = account.getChartOfAccountsCode();
                                    chartCodeCache.put(accountNumber, replacementChartOfAccountsCode);
                                }
                            }
                        }

                        if (!nonExistent && !multipleFound) {
                            StringBuilder buf = new StringBuilder(originEntry.length());
                            buf.append(
                                    originEntry.substring(0, getInclusiveChartOfAccountsCodeStartPosition()));
                            buf.append(replacementChartOfAccountsCode);
                            buf.append(originEntry.subSequence(getExclusiveChartOfAccountsCodeEndPosition(),
                                    originEntry.length()));
                            outputLine = buf.toString();
                        }
                    }
                }
            }
            outputStream.printf("%s\n", outputLine);
            outputLines++;
        }
    } finally {
        outputStream.close();
    }
    return new PreScrubberReportData(inputLines, outputLines, nonExistentAccountCache, multipleAccountCache);
}

From source file:org.distantshoresmedia.keyboard.LatinIME.java

private void initSuggestPuncList() {
    mSuggestPuncList = new ArrayList<CharSequence>();
    String suggestPuncs = sKeyboardSettings.suggestedPunctuation;
    String defaultPuncs = getResources().getString(R.string.suggested_punctuations_default);
    if (suggestPuncs.equals(defaultPuncs) || suggestPuncs.equals("")) {
        // Not user-configured, load the language-specific default.
        suggestPuncs = getResources().getString(R.string.suggested_punctuations);
    }/*  w ww .  java 2 s.  c  om*/
    if (suggestPuncs != null) {
        for (int i = 0; i < suggestPuncs.length(); i++) {
            mSuggestPuncList.add(suggestPuncs.subSequence(i, i + 1));
        }
    }
    setNextSuggestions();
}