Example usage for java.util Deque push

List of usage examples for java.util Deque push

Introduction

In this page you can find the example usage for java.util Deque push.

Prototype

void push(E e);

Source Link

Document

Pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.

Usage

From source file:net.solarnetwork.util.JavaBeanXmlSerializer.java

/**
 * Parse XML into a simple Map structure.
 * /*ww  w  .ja v a2s . c o m*/
 * @param in
 *        the input stream to parse
 * @return a Map of the XML
 */
public Map<String, Object> parseXml(InputStream in) {
    Deque<Map<String, Object>> stack = new LinkedList<Map<String, Object>>();
    Map<String, Object> result = null;
    XMLStreamReader reader = startParse(in);
    try {
        int eventType;
        boolean parsing = true;
        while (parsing) {
            eventType = reader.next();
            switch (eventType) {
            case XMLStreamConstants.END_DOCUMENT:
                parsing = false;
                break;

            case XMLStreamConstants.START_ELEMENT:
                String name = reader.getLocalName();
                if (stack.isEmpty()) {
                    result = new LinkedHashMap<String, Object>();
                    stack.push(result);
                } else {
                    Map<String, Object> el = new LinkedHashMap<String, Object>();
                    putMapValue(stack.peek(), name, el);
                    stack.push(el);
                }
                parseElement(stack.peek(), reader);
                break;

            case XMLStreamConstants.END_ELEMENT:
                stack.pop();
                break;

            }
        }
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } finally {
        endParse(reader);
    }
    return result;
}

From source file:org.apache.asterix.om.typecomputer.impl.RecordRemoveFieldsTypeComputer.java

private IAType buildOutputType(Deque<String> fieldPathStack, ARecordType inputRecordType,
        Set<String> fieldNameSet, List<List<String>> pathList) throws AlgebricksException {
    List<String> resultFieldNames = new ArrayList<>();
    List<IAType> resultFieldTypes = new ArrayList<>();

    String[] fieldNames = inputRecordType.getFieldNames();
    IAType[] fieldTypes = inputRecordType.getFieldTypes();

    for (int i = 0; i < fieldNames.length; i++) {
        if (!fieldNameSet.contains(fieldNames[i])) { // The main field is to be kept
            addField(inputRecordType, fieldNames[i], resultFieldNames, resultFieldTypes);
        } else if (!pathList.isEmpty()) { // Further check needed for nested fields
            if (fieldTypes[i].getTypeTag() == ATypeTag.RECORD) {
                ARecordType subRecord = (ARecordType) fieldTypes[i];

                fieldPathStack.push(fieldNames[i]);
                subRecord = deepCheckAndCopy(fieldPathStack, subRecord, pathList, inputRecordType.isOpen());
                fieldPathStack.pop();//from w  w  w .  j  a  va 2s.  com
                if (subRecord != null) {
                    resultFieldNames.add(fieldNames[i]);
                    resultFieldTypes.add(subRecord);
                }
            }
        }
    }

    int n = resultFieldNames.size();
    String resultTypeName = "result-record(" + inputRecordType.getTypeName() + ")";

    return new ARecordType(resultTypeName, resultFieldNames.toArray(new String[n]),
            resultFieldTypes.toArray(new IAType[n]), true); // Make the output type open always

}

From source file:org.apache.hadoop.hive.ql.parse.PTFTranslator.java

private void translatePTFChain() throws SemanticException {

    Deque<PTFInputSpec> ptfChain = new ArrayDeque<PTFInvocationSpec.PTFInputSpec>();
    PTFInputSpec currentSpec = ptfInvocation.getFunction();
    while (currentSpec != null) {
        ptfChain.push(currentSpec);
        currentSpec = currentSpec.getInput();
    }//from   w  w w . j ava2  s  .  com

    int inputNum = 0;
    PTFInputDef currentDef = null;
    while (!ptfChain.isEmpty()) {
        currentSpec = ptfChain.pop();

        if (currentSpec instanceof PTFQueryInputSpec) {
            currentDef = translate((PTFQueryInputSpec) currentSpec, inputNum);
        } else {
            currentDef = translate((PartitionedTableFunctionSpec) currentSpec, currentDef, inputNum);
        }
        inputNum++;
    }
    ptfDesc.setFuncDef((PartitionedTableFunctionDef) currentDef);
}

From source file:io.bibleget.HTTPCaller.java

/**
 *
 * @param myQuery//from w w  w .  jav a2  s.  co  m
 * @param selectedVersions
 * @return
 * @throws java.lang.ClassNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */
public boolean integrityCheck(String myQuery, List<String> selectedVersions)
        throws ClassNotFoundException, UnsupportedEncodingException {
    String versionsStr = StringUtils.join(selectedVersions.toArray(), ',');
    //System.out.println("Starting integrity check on query "+myQuery+" for versions: "+versionsStr);
    if (indexes == null) {
        indexes = Indexes.getInstance();
    }
    //build indexes based on versions

    //final result is true until proved false
    //set finFlag to false for non-breaking errors, or simply return false for breaking errors
    boolean finFlag = true;

    errorMessages.removeAll(errorMessages);
    List<String> queries = new ArrayList<>();

    //if english notation is found, translate to european notation
    if (myQuery.contains(":") && myQuery.contains(".")) {
        errorMessages.add(__(
                "Mixed notations have been detected. Please use either english notation or european notation."));
        return false;
    } else if (myQuery.contains(":")) {
        if (myQuery.contains(",")) {
            myQuery = myQuery.replace(",", ".");
        }
        myQuery = myQuery.replace(":", ",");
    }

    if (myQuery.isEmpty() == false) {
        if (myQuery.contains(";")) {
            //System.out.println("We have a semicolon");
            queries.addAll(Arrays.asList(myQuery.split(";")));
            for (Iterator<String> it = queries.iterator(); it.hasNext();) {
                if (it.next().isEmpty()) {
                    it.remove(); // NOTE: Iterator's remove method, not ArrayList's, is used.
                }
            }
        } else {
            //System.out.println("There is no semicolon");
            queries.add(myQuery);
        }
    }

    boolean first = true;
    String currBook = "";

    if (queries.isEmpty()) {
        errorMessages.add(__("You cannot send an empty query."));
        return false;
    }
    for (String querie : queries) {
        //System.out.println(querie);
        querie = toProperCase(querie);
        //System.out.println(querie);

        //RULE 1: at least the first query must have a book indicator
        if (first) {
            if (querie.matches("^[1-3]{0,1}((\\p{L}\\p{M}*)+)(.*)") == false) {
                errorMessages.add(MessageFormat.format(__(
                        "The first query <{0}> in the querystring <{1}> must start with a valid book indicator!"),
                        querie, myQuery));
                finFlag = false;
            }
            first = false;
        }

        //RULE 2: for every query that starts with a book indicator, 
        //        the book indicator must be followed by valid chapter indicator;
        //        else query must start with valid chapter indicator
        int bBooksContains;
        int myidx = -1;
        String tempBook = "";
        if (querie.matches("^[1-3]{0,1}((\\p{L}\\p{M}*)+)(.*)") == true) {
            //while we're at it, let's capture the book value from the query
            Pattern pattern = Pattern.compile("^[1-3]{0,1}((\\p{L}\\p{M}*)+)", Pattern.UNICODE_CHARACTER_CLASS);
            Matcher matcher = pattern.matcher(querie);
            if (matcher.find()) {
                tempBook = matcher.group();
                bBooksContains = isValidBook(tempBook);
                myidx = bBooksContains + 1;
                //if(bBooksContains == false && bBooksAbbrevsContains == false){
                if (bBooksContains == -1) {
                    errorMessages.add(MessageFormat.format(__(
                            "The book indicator <{0}> in the query <{1}> is not valid. Please check the documentation for a list of valid book indicators."),
                            tempBook, querie));
                    finFlag = false;
                } else {
                    //if(bBooksContains)
                    currBook = tempBook;
                    //querie = querie.replace(tempBook,"");
                }
            }

            Pattern pattern1 = Pattern.compile("^[1-3]{0,1}((\\p{L}\\p{M}*)+)",
                    Pattern.UNICODE_CHARACTER_CLASS);
            Pattern pattern2 = Pattern.compile("^[1-3]{0,1}((\\p{L}\\p{M}*)+)[1-9][0-9]{0,2}",
                    Pattern.UNICODE_CHARACTER_CLASS);
            Matcher matcher1 = pattern1.matcher(querie);
            Matcher matcher2 = pattern2.matcher(querie);
            int count1 = 0;
            while (matcher1.find()) {
                count1++;
            }
            int count2 = 0;
            while (matcher2.find()) {
                count2++;
            }
            if (querie.matches("^[1-3]{0,1}((\\p{L}\\p{M}*)+)[1-9][0-9]{0,2}(.*)") == false
                    || count1 != count2) {
                errorMessages.add(__("You must have a valid chapter following the book indicator!"));
                finFlag = false;
            }
            querie = querie.replace(tempBook, "");
        } else {
            if (querie.matches("^[1-9][0-9]{0,2}(.*)") == false) {
                errorMessages.add(__(
                        "A query that doesn't start with a book indicator must however start with a valid chapter indicator!"));
                finFlag = false;
            }
        }

        //RULE 3: Queries with a dot operator must first have a comma operator; and cannot have more commas than dots
        if (querie.contains(".")) {
            Pattern pattern11 = Pattern.compile("[,|\\-|\\.][1-9][0-9]{0,2}\\.");
            Matcher matcher11 = pattern11.matcher(querie);
            if (querie.contains(",") == false || matcher11.find() == false) {
                errorMessages.add(__(
                        "You cannot use a dot without first using a comma or a dash. A dot is a liason between verses, which are separated from the chapter by a comma."));
                finFlag = false;
            }
            Pattern pattern3 = Pattern.compile("(?<![0-9])(?=(([1-9][0-9]{0,2})\\.([1-9][0-9]{0,2})))");
            Matcher matcher3 = pattern3.matcher(querie);
            int count = 0;
            while (matcher3.find()) {
                //RULE 4: verse numbers around dot operators must be sequential
                if (Integer.parseInt(matcher3.group(2)) >= Integer.parseInt(matcher3.group(3))) {
                    errorMessages.add(MessageFormat.format(__(
                            "Verses concatenated by a dot must be consecutive, instead <{0}> is greater than or equal to <{1}> in the expression <{2}> in the query <{3}>"),
                            matcher3.group(2), matcher3.group(3), matcher3.group(1), querie));
                    finFlag = false;
                }
                count++;
            }
            //RULE 5: Dot operators must be preceded and followed by a number from one to three digits, of which the first digit cannot be a 0
            if (count == 0 || count != StringUtils.countMatches(querie, ".")) {
                errorMessages.add(__(
                        "A dot must be preceded and followed by 1 to 3 digits of which the first digit cannot be zero.")
                        + " <" + querie + ">");
                finFlag = false;
            }
        }

        //RULE 6: Comma operators must be preceded and followed by a number from one to three digits, of which the first digit cannot be 0
        if (querie.contains(",")) {

            Pattern pattern4 = Pattern.compile("([1-9][0-9]{0,2})\\,[1-9][0-9]{0,2}");
            Matcher matcher4 = pattern4.matcher(querie);
            int count = 0;
            List<Integer> chapters = new ArrayList<>();
            while (matcher4.find()) {
                //System.out.println("group0="+matcher4.group(0)+", group1="+matcher4.group(1));
                chapters.add(Integer.parseInt(matcher4.group(1)));
                count++;
            }
            if (count == 0 || count != StringUtils.countMatches(querie, ",")) {
                errorMessages.add(__(
                        "A comma must be preceded and followed by 1 to 3 digits of which the first digit cannot be zero.")
                        + " <" + querie + ">" + "(count=" + Integer.toString(count) + ",comma count="
                        + StringUtils.countMatches(querie, ",") + "); chapters=" + chapters.toString());
                finFlag = false;
            } else {
                // let's check the validity of the chapter numbers against the version indexes
                //for each chapter captured in the querystring
                for (int chapter : chapters) {
                    if (indexes.isValidChapter(chapter, myidx, selectedVersions) == false) {
                        int[] chapterLimit = indexes.getChapterLimit(myidx, selectedVersions);
                        errorMessages.add(MessageFormat.format(__(
                                "A chapter in the query is out of bounds: there is no chapter <{0}> in the book <{1}> in the requested version <{2}>, the last possible chapter is <{3}>"),
                                Integer.toString(chapter), currBook, StringUtils.join(selectedVersions, ","),
                                StringUtils.join(chapterLimit, ',')));
                        finFlag = false;
                    }
                }
            }
        }

        if (StringUtils.countMatches(querie, ",") > 1) {
            if (!querie.contains("-")) {
                errorMessages.add(__("You cannot have more than one comma and not have a dash!"));
                finFlag = false;
            }
            String[] parts = StringUtils.split(querie, "-");
            if (parts.length != 2) {
                errorMessages
                        .add(__("You seem to have a malformed querystring, there should be only one dash."));
                finFlag = false;
            }
            for (String p : parts) {
                Integer[] pp = new Integer[2];
                String[] tt = StringUtils.split(p, ",");
                int x = 0;
                for (String t : tt) {
                    pp[x++] = Integer.parseInt(t);
                }
                if (indexes.isValidChapter(pp[0], myidx, selectedVersions) == false) {
                    int[] chapterLimit;
                    chapterLimit = indexes.getChapterLimit(myidx, selectedVersions);
                    //                        System.out.print("chapterLimit = ");
                    //                        System.out.println(Arrays.toString(chapterLimit));
                    errorMessages.add(MessageFormat.format(__(
                            "A chapter in the query is out of bounds: there is no chapter <{0}> in the book <{1}> in the requested version <{2}>, the last possible chapter is <{3}>"),
                            Integer.toString(pp[0]), currBook, StringUtils.join(selectedVersions, ","),
                            StringUtils.join(chapterLimit, ',')));
                    finFlag = false;
                } else {
                    if (indexes.isValidVerse(pp[1], pp[0], myidx, selectedVersions) == false) {
                        int[] verseLimit = indexes.getVerseLimit(pp[0], myidx, selectedVersions);
                        //                            System.out.print("verseLimit = ");
                        //                            System.out.println(Arrays.toString(verseLimit));
                        errorMessages.add(MessageFormat.format(__(
                                "A verse in the query is out of bounds: there is no verse <{0}> in the book <{1}> at chapter <{2}> in the requested version <{3}>, the last possible verse is <{4}>"),
                                Integer.toString(pp[1]), currBook, Integer.toString(pp[0]),
                                StringUtils.join(selectedVersions, ","), StringUtils.join(verseLimit, ',')));
                        finFlag = false;
                    }
                }
            }
        } else if (StringUtils.countMatches(querie, ",") == 1) {
            String[] parts = StringUtils.split(querie, ",");
            //System.out.println(Arrays.toString(parts));
            if (indexes.isValidChapter(Integer.parseInt(parts[0]), myidx, selectedVersions) == false) {
                int[] chapterLimit = indexes.getChapterLimit(myidx, selectedVersions);
                errorMessages.add(MessageFormat.format(__(
                        "A chapter in the query is out of bounds: there is no chapter <{0}> in the book <{1}> in the requested version <{2}>, the last possible chapter is <{3}>"),
                        parts[0], currBook, StringUtils.join(selectedVersions, ","),
                        StringUtils.join(chapterLimit, ',')));
                finFlag = false;
            } else {
                if (parts[1].contains("-")) {
                    Deque<Integer> highverses = new ArrayDeque<>();
                    Pattern pattern11 = Pattern.compile("[,\\.][1-9][0-9]{0,2}\\-([1-9][0-9]{0,2})");
                    Matcher matcher11 = pattern11.matcher(querie);
                    while (matcher11.find()) {
                        highverses.push(Integer.parseInt(matcher11.group(1)));
                    }
                    int highverse = highverses.pop();
                    if (indexes.isValidVerse(highverse, Integer.parseInt(parts[0]), myidx,
                            selectedVersions) == false) {
                        int[] verseLimit = indexes.getVerseLimit(Integer.parseInt(parts[0]), myidx,
                                selectedVersions);
                        errorMessages.add(MessageFormat.format(__(
                                "A verse in the query is out of bounds: there is no verse <{0}> in the book <{1}> at chapter <{2}> in the requested version <{3}>, the last possible verse is <{4}>"),
                                highverse, currBook, parts[0], StringUtils.join(selectedVersions, ","),
                                StringUtils.join(verseLimit, ',')));
                        finFlag = false;
                    }
                } else {
                    Pattern pattern12 = Pattern.compile(",([1-9][0-9]{0,2})");
                    Matcher matcher12 = pattern12.matcher(querie);
                    int highverse = -1;
                    while (matcher12.find()) {
                        highverse = Integer.parseInt(matcher12.group(1));
                        //System.out.println("[line 376]:highverse="+Integer.toString(highverse));
                    }
                    if (highverse != -1) {
                        //System.out.println("Checking verse validity for book "+myidx+" chapter "+parts[0]+"...");
                        if (indexes.isValidVerse(highverse, Integer.parseInt(parts[0]), myidx,
                                selectedVersions) == false) {
                            int[] verseLimit = indexes.getVerseLimit(Integer.parseInt(parts[0]), myidx,
                                    selectedVersions);
                            errorMessages.add(MessageFormat.format(__(
                                    "A verse in the query is out of bounds: there is no verse <{0}> in the book <{1}> at chapter <{2}> in the requested version <{3}>, the last possible verse is <{4}>"),
                                    highverse, currBook, parts[0], StringUtils.join(selectedVersions, ","),
                                    StringUtils.join(verseLimit, ',')));
                            finFlag = false;
                        }
                    }
                }
                Pattern pattern13 = Pattern.compile("\\.([1-9][0-9]{0,2})$");
                Matcher matcher13 = pattern13.matcher(querie);
                int highverse = -1;
                while (matcher13.find()) {
                    highverse = Integer.parseInt(matcher13.group(1));
                }
                if (highverse != -1) {
                    if (indexes.isValidVerse(highverse, Integer.parseInt(parts[0]), myidx,
                            selectedVersions) == false) {
                        int[] verseLimit = indexes.getVerseLimit(Integer.parseInt(parts[0]), myidx,
                                selectedVersions);
                        errorMessages.add(MessageFormat.format(__(
                                "A verse in the query is out of bounds: there is no verse <{0}> in the book <{1}> at chapter <{2}> in the requested version <{3}>, the last possible verse is <{4}>"),
                                highverse, currBook, parts[0], StringUtils.join(selectedVersions, ","),
                                StringUtils.join(verseLimit, ',')));
                        finFlag = false;
                    }
                }
            }
        } else { //if there is no comma, it's either a single chapter or an extension of chapters with a dash
                 //System.out.println("no comma found");
            String[] parts = StringUtils.split(querie, "-");
            //System.out.println(Arrays.toString(parts));
            int highchapter = Integer.parseInt(parts[parts.length - 1]);
            if (indexes.isValidChapter(highchapter, myidx, selectedVersions) == false) {
                int[] chapterLimit = indexes.getChapterLimit(myidx, selectedVersions);
                errorMessages.add(MessageFormat.format(__(
                        "A chapter in the query is out of bounds: there is no chapter <{0}> in the book <{1}> in the requested version <{2}>, the last possible chapter is <{3}>"),
                        Integer.toString(highchapter), currBook, StringUtils.join(selectedVersions, ","),
                        StringUtils.join(chapterLimit, ',')));
                finFlag = false;
            }
        }

        if (querie.contains("-")) {
            //RULE 7: If there are multiple dashes in a query, there cannot be more dashes than there are dots minus 1
            int dashcount = StringUtils.countMatches(querie, "-");
            int dotcount = StringUtils.countMatches(querie, ".");
            if (dashcount > 1) {
                if (dashcount - 1 > dotcount) {
                    errorMessages.add(__(
                            "There are multiple dashes in the query, but there are not enough dots. There can only be one more dash than dots.")
                            + " <" + querie + ">");
                    finFlag = false;
                }
            }

            //RULE 8: Dash operators must be preceded and followed by a number from one to three digits, of which the first digit cannot be 0
            Pattern pattern5 = Pattern.compile("([1-9][0-9]{0,2}\\-[1-9][0-9]{0,2})");
            Matcher matcher5 = pattern5.matcher(querie);
            int count = 0;
            while (matcher5.find()) {
                count++;
            }
            if (count == 0 || count != StringUtils.countMatches(querie, "-")) {
                errorMessages.add(__(
                        "A dash must be preceded and followed by 1 to 3 digits of which the first digit cannot be zero.")
                        + " <" + querie + ">");
                finFlag = false;
            }

            //RULE 9: If a comma construct follows a dash, there must also be a comma construct preceding the dash
            Pattern pattern6 = Pattern.compile("\\-([1-9][0-9]{0,2})\\,");
            Matcher matcher6 = pattern6.matcher(querie);
            if (matcher6.find()) {
                Pattern pattern7 = Pattern.compile("\\,[1-9][0-9]{0,2}\\-");
                Matcher matcher7 = pattern7.matcher(querie);
                if (matcher7.find() == false) {
                    errorMessages.add(__(
                            "If there is a chapter-verse construct following a dash, there must also be a chapter-verse construct preceding the same dash.")
                            + " <" + querie + ">");
                    finFlag = false;
                } else {
                    //RULE 10: Chapters before and after dashes must be sequential
                    int chap1 = -1;
                    int chap2 = -1;

                    Pattern pattern8 = Pattern.compile("([1-9][0-9]{0,2})\\,[1-9][0-9]{0,2}\\-");
                    Matcher matcher8 = pattern8.matcher(querie);
                    if (matcher8.find()) {
                        chap1 = Integer.parseInt(matcher8.group(1));
                    }
                    Pattern pattern9 = Pattern.compile("\\-([1-9][0-9]{0,2})\\,");
                    Matcher matcher9 = pattern9.matcher(querie);
                    if (matcher9.find()) {
                        chap2 = Integer.parseInt(matcher9.group(1));
                    }

                    if (chap1 >= chap2) {
                        errorMessages.add(MessageFormat.format(__(
                                "Chapters must be consecutive. Instead the first chapter indicator <{0}> is greater than or equal to the second chapter indicator <{1}> in the expression <{2}>"),
                                chap1, chap2, querie));
                        finFlag = false;
                    }
                }
            } else {
                //if there are no comma constructs immediately following the dash
                //RULE 11: Verses (or chapters if applicable) around each of the dash operator(s) must be sequential
                Pattern pattern10 = Pattern.compile("([1-9][0-9]{0,2})\\-([1-9][0-9]{0,2})");
                Matcher matcher10 = pattern10.matcher(querie);
                while (matcher10.find()) {
                    int num1 = Integer.parseInt(matcher10.group(1));
                    int num2 = Integer.parseInt(matcher10.group(2));
                    if (num1 >= num2) {
                        errorMessages.add(MessageFormat.format(__(
                                "Verses (or chapters if applicable) around the dash operator must be consecutive. Instead <{0}> is greater than or equal to <{1}> in the expression <{2}>"),
                                num1, num2, querie));
                        finFlag = false;
                    }
                }

            }
        }

    }

    return finFlag;
}

From source file:org.apache.hadoop.hive.ql.QTestUtil2.java

/**
 * Given the current configurations (e.g., hadoop version and execution
 * mode), return the correct file name to compare with the current test run
 * output./*from  ww w. j  av  a2  s.  c o m*/
 * 
 * @param outDir
 *            The directory where the reference log files are stored.
 * @param testName
 *            The test file name (terminated by ".out").
 * @return The file name appended with the configuration values if it
 *         exists.
 */
public String outPath(String outDir, String testName) {
    String ret = (new File(outDir, testName)).getPath();
    // List of configurations. Currently the list consists of hadoop version
    // and execution mode only
    List<String> configs = new ArrayList<String>();
    configs.add(this.hadoopVer);

    Deque<String> stack = new LinkedList<String>();
    StringBuilder sb = new StringBuilder();
    sb.append(testName);
    stack.push(sb.toString());

    // example file names are input1.q.out_0.20.0_minimr or
    // input2.q.out_0.17
    for (String s : configs) {
        sb.append('_');
        sb.append(s);
        stack.push(sb.toString());
    }
    while (stack.size() > 0) {
        String fileName = stack.pop();
        File f = new File(outDir, fileName);
        if (f.exists()) {
            ret = f.getPath();
            break;
        }
    }
    return ret;
}

From source file:org.apache.phoenix.hive.HiveTestUtil.java

/**
 * Given the current configurations (e.g., hadoop version and execution mode), return
 * the correct file name to compare with the current test run output.
 *
 * @param outDir   The directory where the reference log files are stored.
 * @param testName The test file name (terminated by ".out").
 * @return The file name appended with the configuration values if it exists.
 *///from w  w w  . j a v a  2s .  c o m
public String outPath(String outDir, String testName) {
    String ret = (new File(outDir, testName)).getPath();
    // List of configurations. Currently the list consists of hadoop version and execution
    // mode only
    List<String> configs = new ArrayList<String>();
    configs.add(this.hadoopVer);

    Deque<String> stack = new LinkedList<String>();
    StringBuilder sb = new StringBuilder();
    sb.append(testName);
    stack.push(sb.toString());

    // example file names are input1.q.out_0.20.0_minimr or input2.q.out_0.17
    for (String s : configs) {
        sb.append('_');
        sb.append(s);
        stack.push(sb.toString());
    }
    while (stack.size() > 0) {
        String fileName = stack.pop();
        File f = new File(outDir, fileName);
        if (f.exists()) {
            ret = f.getPath();
            break;
        }
    }
    return ret;
}

From source file:jetbrains.exodus.entitystore.FileSystemBlobVaultOld.java

@Override
public BackupStrategy getBackupStrategy() {
    return new BackupStrategy() {

        @Override//from www .  j a va  2s. c  om
        public Iterable<FileDescriptor> listFiles() {
            return new Iterable<FileDescriptor>() {
                @Override
                public Iterator<FileDescriptor> iterator() {
                    final Deque<FileDescriptor> queue = new LinkedList<>();
                    queue.add(new FileDescriptor(location, blobsDirectory + File.separator));
                    return new Iterator<FileDescriptor>() {
                        int i = 0;
                        int n = 0;
                        File[] files;
                        FileDescriptor next;
                        String currentPrefix;

                        @Override
                        public boolean hasNext() {
                            if (next != null) {
                                return true;
                            }
                            while (i < n) {
                                final File file = files[i++];
                                final String name = file.getName();
                                if (file.isDirectory()) {
                                    queue.push(new FileDescriptor(file,
                                            currentPrefix + file.getName() + File.separator));
                                } else if (file.isFile()) {
                                    final long fileSize = file.length();
                                    if (fileSize == 0)
                                        continue;
                                    if (name.endsWith(blobExtension) || name.equalsIgnoreCase(VERSION_FILE)) {
                                        next = new FileDescriptor(file, currentPrefix, fileSize);
                                        return true;
                                    }
                                } else {
                                    // something strange with filesystem
                                    throw new EntityStoreException(
                                            "File or directory expected: " + file.toString());
                                }
                            }
                            if (queue.isEmpty()) {
                                return false;
                            }
                            final FileDescriptor fd = queue.pop();
                            files = IOUtil.listFiles(fd.getFile());
                            currentPrefix = fd.getPath();
                            i = 0;
                            n = files.length;
                            next = fd;
                            return true;
                        }

                        @Override
                        public FileDescriptor next() {
                            if (!hasNext()) {
                                throw new NoSuchElementException();
                            }
                            final FileDescriptor result = next;
                            next = null;
                            return result;
                        }

                        @Override
                        public void remove() {
                            throw new UnsupportedOperationException();
                        }
                    };
                }
            };
        }
    };
}

From source file:org.lilyproject.repository.impl.HBaseTypeManager.java

private RecordType updateRecordType(RecordType recordType, boolean refreshSubtypes, Deque<SchemaId> parents)
        throws RepositoryException, InterruptedException {
    // First update the record type
    RecordType updatedRecordType = updateRecordType(recordType);

    if (!refreshSubtypes) {
        return updatedRecordType;
    }//from  ww w  . j av  a 2 s . co m

    parents.push(updatedRecordType.getId());

    try {
        Set<SchemaId> subtypes = findDirectSubtypes(updatedRecordType.getId());

        for (SchemaId subtype : subtypes) {
            if (!parents.contains(subtype)) {
                RecordType subRecordType = getRecordTypeById(subtype, null);
                for (Map.Entry<SchemaId, Long> supertype : subRecordType.getSupertypes().entrySet()) {
                    if (supertype.getKey().equals(updatedRecordType.getId())) {
                        if (!supertype.getValue().equals(updatedRecordType.getVersion())) {
                            subRecordType.addSupertype(updatedRecordType.getId(),
                                    updatedRecordType.getVersion());
                            // Store the change, and recursively adjust the pointers in this record type's subtypes as well
                            updateRecordType(subRecordType, true, parents);
                        }
                        break;
                    }
                }
            } else {
                // Loop detected in type hierarchy, log a warning about this
                log.warn(formatSupertypeLoopError(subtype, parents));
            }
        }
    } catch (RepositoryException e) {
        throw new RepositoryException("Error while refreshing subtypes of record type " + recordType.getName(),
                e);
    }

    parents.pop();

    return updatedRecordType;
}

From source file:com.datastax.loader.CqlDelimLoad.java

public boolean run(String[] args)
        throws IOException, ParseException, InterruptedException, ExecutionException, KeyStoreException,
        NoSuchAlgorithmException, KeyManagementException, CertificateException, UnrecoverableKeyException {
    if (false == parseArgs(args)) {
        System.err.println("Bad arguments");
        System.err.println(usage());
        return false;
    }//from  w  w w.  ja  va2  s.com

    // Setup
    if (false == setup())
        return false;

    // open file
    Deque<File> fileList = new ArrayDeque<File>();
    File infile = null;
    File[] inFileList = null;
    boolean onefile = true;
    if (STDIN.equalsIgnoreCase(filename)) {
        infile = null;
    } else {
        infile = new File(filename);
        if (infile.isFile()) {
        } else {
            inFileList = infile.listFiles();
            if (inFileList.length < 1)
                throw new IOException("directory is empty");
            onefile = false;
            Arrays.sort(inFileList, new Comparator<File>() {
                public int compare(File f1, File f2) {
                    return f1.getName().compareTo(f2.getName());
                }
            });
            for (int i = 0; i < inFileList.length; i++)
                fileList.push(inFileList[i]);
        }
    }

    // Launch Threads
    ExecutorService executor;
    long total = 0;
    if (onefile) {
        // One file/stdin to process
        executor = Executors.newSingleThreadExecutor();
        Callable<Long> worker = new CqlDelimLoadTask(cqlSchema, delimiter, charsPerColumn, nullString,
                commentString, dateFormatString, localDateFormatString, boolStyle, locale, maxErrors, skipRows,
                skipCols, maxRows, badDir, infile, session, consistencyLevel, numFutures, batchSize, numRetries,
                queryTimeout, maxInsertErrors, successDir, failureDir, nullsUnset, format, keyspace, table);
        Future<Long> res = executor.submit(worker);
        total = res.get();
        executor.shutdown();
    } else {
        executor = Executors.newFixedThreadPool(numThreads);
        Set<Future<Long>> results = new HashSet<Future<Long>>();
        while (!fileList.isEmpty()) {
            File tFile = fileList.pop();
            Callable<Long> worker = new CqlDelimLoadTask(cqlSchema, delimiter, charsPerColumn, nullString,
                    commentString, dateFormatString, localDateFormatString, boolStyle, locale, maxErrors,
                    skipRows, skipCols, maxRows, badDir, tFile, session, consistencyLevel, numFutures,
                    batchSize, numRetries, queryTimeout, maxInsertErrors, successDir, failureDir, nullsUnset,
                    format, keyspace, table);
            results.add(executor.submit(worker));
        }
        executor.shutdown();
        for (Future<Long> res : results)
            total += res.get();
    }

    // Cleanup
    cleanup();
    //System.err.println("Total rows inserted: " + total);

    return true;
}

From source file:net.dv8tion.jda.core.entities.impl.ReceivedMessage.java

@Override
public String getContentStripped() {
    if (strippedContent != null)
        return strippedContent;
    synchronized (mutex) {
        if (strippedContent != null)
            return strippedContent;
        String tmp = getContentDisplay();
        //all the formatting keys to keep track of
        String[] keys = new String[] { "*", "_", "`", "~~" };

        //find all tokens (formatting strings described above)
        TreeSet<FormatToken> tokens = new TreeSet<>(Comparator.comparingInt(t -> t.start));
        for (String key : keys) {
            Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp);
            while (matcher.find())
                tokens.add(new FormatToken(key, matcher.start()));
        }// www.j a v a 2  s . co m

        //iterate over all tokens, find all matching pairs, and add them to the list toRemove
        Deque<FormatToken> stack = new ArrayDeque<>();
        List<FormatToken> toRemove = new ArrayList<>();
        boolean inBlock = false;
        for (FormatToken token : tokens) {
            if (stack.isEmpty() || !stack.peek().format.equals(token.format)
                    || stack.peek().start + token.format.length() == token.start)

            {
                //we are at opening tag
                if (!inBlock) {
                    //we are outside of block -> handle normally
                    if (token.format.equals("`")) {
                        //block start... invalidate all previous tags
                        stack.clear();
                        inBlock = true;
                    }
                    stack.push(token);
                } else if (token.format.equals("`")) {
                    //we are inside of a block -> handle only block tag
                    stack.push(token);
                }
            } else if (!stack.isEmpty()) {
                //we found a matching close-tag
                toRemove.add(stack.pop());
                toRemove.add(token);
                if (token.format.equals("`") && stack.isEmpty())
                    //close tag closed the block
                    inBlock = false;
            }
        }

        //sort tags to remove by their start-index and iteratively build the remaining string
        toRemove.sort(Comparator.comparingInt(t -> t.start));
        StringBuilder out = new StringBuilder();
        int currIndex = 0;
        for (FormatToken formatToken : toRemove) {
            if (currIndex < formatToken.start)
                out.append(tmp.substring(currIndex, formatToken.start));
            currIndex = formatToken.start + formatToken.format.length();
        }
        if (currIndex < tmp.length())
            out.append(tmp.substring(currIndex));
        //return the stripped text, escape all remaining formatting characters (did not have matching
        // open/close before or were left/right of block
        return strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");
    }
}