Example usage for org.apache.commons.lang ArrayUtils contains

List of usage examples for org.apache.commons.lang ArrayUtils contains

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils contains.

Prototype

public static boolean contains(boolean[] array, boolean valueToFind) 

Source Link

Document

Checks if the value is in the given array.

Usage

From source file:com.linkedin.pinot.core.predicate.NoDictionaryEqualsPredicateEvaluatorsTest.java

@Test
public void testFloatPredicateEvaluators() {
    // FLOAT data type
    float floatValue = _random.nextFloat();
    EqPredicate eqPredicate = new EqPredicate(COLUMN_NAME,
            Collections.singletonList(Float.toString(floatValue)));
    PredicateEvaluator eqPredicateEvaluator = EqualsPredicateEvaluatorFactory
            .newNoDictionaryBasedEvaluator(eqPredicate, FieldSpec.DataType.FLOAT);

    NEqPredicate neqPredicate = new NEqPredicate(COLUMN_NAME,
            Collections.singletonList(Float.toString(floatValue)));
    PredicateEvaluator neqPredicateEvaluator = NotEqualsPredicateEvaluatorFactory
            .newNoDictionaryBasedEvaluator(neqPredicate, FieldSpec.DataType.FLOAT);

    Assert.assertTrue(eqPredicateEvaluator.apply(floatValue));
    Assert.assertFalse(neqPredicateEvaluator.apply(floatValue));

    float[] randomFloats = new float[NUM_MULTI_VALUES];
    PredicateEvaluatorTestUtils.fillRandom(randomFloats);
    randomFloats[_random.nextInt(randomFloats.length)] = floatValue;

    Assert.assertTrue(eqPredicateEvaluator.apply(randomFloats));
    Assert.assertFalse(neqPredicateEvaluator.apply(randomFloats));

    for (int i = 0; i < 100; i++) {
        float random = _random.nextFloat();
        Assert.assertEquals(eqPredicateEvaluator.apply(random), (random == floatValue));
        Assert.assertEquals(neqPredicateEvaluator.apply(random), (random != floatValue));

        PredicateEvaluatorTestUtils.fillRandom(randomFloats);
        Assert.assertEquals(eqPredicateEvaluator.apply(randomFloats),
                ArrayUtils.contains(randomFloats, floatValue));
        Assert.assertEquals(neqPredicateEvaluator.apply(randomFloats),
                !ArrayUtils.contains(randomFloats, floatValue));
    }/*ww w.  j a v a  2s  . com*/
}

From source file:de.tudarmstadt.ukp.dkpro.core.testing.harness.SegmenterHarness.java

public static void run(AnalysisEngineDescription aAed, String... aIgnoreIds) throws Throwable {
    AnalysisEngine ae = createEngine(aAed);
    JCas jCas = ae.newJCas();//w w w  . j a va2 s  .  c  om

    List<String> results = new ArrayList<String>();

    try {
        for (TestData td : DATA) {
            System.out.printf("== %s ==%n", td.id);
            jCas.reset();
            jCas.setDocumentLanguage(td.language);
            jCas.setDocumentText(td.text);

            boolean failed = false;

            try {
                ae.process(jCas);

                AssertAnnotations.assertSentence(td.sentences, select(jCas, Sentence.class));
                AssertAnnotations.assertToken(td.tokens, select(jCas, Token.class));

                results.add(String.format("%s OK", td.id));
            } catch (Throwable e) {
                failed = true;
                if (!ArrayUtils.contains(aIgnoreIds, td.id)) {
                    results.add(String.format("%s FAIL", td.id));
                    throw e;
                } else {
                    results.add(String.format("%s FAIL - Known, ignored", td.id));
                }
            }

            if (!failed && ArrayUtils.contains(aIgnoreIds, td.id)) {
                results.add(String.format("%s FAIL", td.id));
                Assert.fail(td.id + " passed but was expected to fail");
            }
        }
    } finally {
        System.out.println("=== RESULTS ===");
        for (String r : results) {
            System.out.println(r);
        }
    }
}

From source file:info.magnolia.cms.taglibs.util.SimpleSearchTag.java

/**
 * Split search terms and build an xpath query in the form:
 * <code>//*[@jcr:primaryType='mgnl:content']/\*\/\*[jcr:contains(., 'first') or jcr:contains(., 'second')]</code>
 *
 * @return valid xpath expression or null if the given query doesn't contain at least one valid search term
 *///from   w  ww .  j a v a  2 s . c o m
protected String generateXPathQuery() {

    String startPath = null;

    // search only in a specific subtree
    if (this.startLevel != 0) {
        try {
            Content activePage = Resource.getActivePage((HttpServletRequest) this.pageContext.getRequest());
            if (activePage != null) {
                startPath = StringUtils.strip(activePage.getAncestor(this.startLevel).getHandle(), "/"); //$NON-NLS-1$
            }
        } catch (RepositoryException e) {
            log.error(e.getMessage(), e);
        }
    }

    // strip reserved chars and split
    String[] tokens = StringUtils
            .split(StringUtils.lowerCase(StringUtils.replaceChars(this.query, RESERVED_CHARS, null)));

    // null input string?
    if (tokens == null) {
        return null;
    }

    StringBuffer xpath = new StringBuffer(tokens.length * 20);
    if (StringUtils.isNotEmpty(startPath)) {
        xpath.append(startPath);
    }
    xpath.append("//*[@jcr:primaryType=\'mgnl:content\']/*/*["); //$NON-NLS-1$

    String joinOperator = "and"; //$NON-NLS-1$
    boolean emptyQuery = true;

    for (int j = 0; j < tokens.length; j++) {
        String tkn = tokens[j];
        if (ArrayUtils.contains(KEYWORDS, tkn)) {
            joinOperator = tkn;
        } else {
            if (!emptyQuery) {
                xpath.append(" "); //$NON-NLS-1$
                xpath.append(joinOperator);
                xpath.append(" "); //$NON-NLS-1$
            }
            xpath.append("jcr:contains(., '"); //$NON-NLS-1$
            xpath.append(tkn);
            xpath.append("')"); //$NON-NLS-1$
            emptyQuery = false;
        }

    }

    xpath.append("]"); //$NON-NLS-1$

    // if no valid search terms are added don't return a catch-all query
    if (emptyQuery) {
        return null;
    }

    return xpath.toString();
}

From source file:com.flexive.core.conversion.FxTypeConverter.java

/**
 * {@inheritDoc}//from  w ww .  j  a  v a 2  s  .c  o  m
 */
@Override
@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext ctx) {
    FxType type = ((FxType) o);
    FxEnvironment env = CacheAdmin.getEnvironment();
    try {
        writer.addAttribute("name", type.getName());
        writer.addAttribute("derived", String.valueOf(type.isDerived()));
        if (type.isDerived())
            writer.addAttribute("parent", type.getParent().getName());

        writer.addAttribute("acl", type.getACL().getName());
        writer.addAttribute("hasdefacl", String.valueOf(type.hasDefaultInstanceACL()));
        if (type.hasDefaultInstanceACL())
            writer.addAttribute("defacl", type.getDefaultInstanceACL().getName());
        writer.addAttribute("category", type.getCategory().name());
        writer.addAttribute("languageMode", type.getLanguage().name());
        writer.addAttribute("maxVersions", String.valueOf(type.getMaxVersions()));
        writer.addAttribute("autoVersion", String.valueOf(type.isAutoVersion()));
        writer.addAttribute("includedInSuperTypeQueries", String.valueOf(type.isIncludedInSupertypeQueries()));
        writer.addAttribute("mode", type.getMode().name());
        writer.addAttribute("state", type.getState().name());
        writer.addAttribute("storageMode", type.getStorageMode().name());
        writer.addAttribute("workflow", type.getWorkflow().getName());
        writer.addAttribute("permType", String.valueOf(type.isUseTypePermissions()));
        writer.addAttribute("permProp", String.valueOf(type.isUsePropertyPermissions()));
        writer.addAttribute("permInst", String.valueOf(type.isUseInstancePermissions()));
        writer.addAttribute("permStep", String.valueOf(type.isUseStepPermissions()));

        writer.addAttribute("trackHistory", String.valueOf(type.isTrackHistory()));
        if (type.isTrackHistory())
            writer.addAttribute("historyAge", String.valueOf(type.getHistoryAge()));

        if (type.isRelation()) {
            writer.startNode("relations");
            writer.addAttribute("maxSrc", String.valueOf(type.getMaxRelSource()));
            writer.addAttribute("maxDst", String.valueOf(type.getMaxRelDestination()));
            for (FxTypeRelation rel : type.getRelations()) {
                writer.startNode("relation");
                writer.addAttribute("src", rel.getSource().getName());
                writer.addAttribute("maxSrc", String.valueOf(rel.getMaxSource()));
                writer.addAttribute("dst", rel.getDestination().getName());
                writer.addAttribute("maxDst", String.valueOf(rel.getMaxDestination()));
                writer.endNode();
            }
            writer.endNode();
        }

        writer.startNode("label");
        ctx.convertAnother(type.getLabel());
        writer.endNode();

        ctx.convertAnother(type.getLifeCycleInfo());

        if (!type.getScriptEvents().isEmpty()) {
            writer.startNode("scriptEvents");
            for (FxScriptEvent event : type.getScriptEvents()) {
                for (long script : type.getScriptMapping(event)) {
                    writer.startNode("scriptMapping");
                    writer.addAttribute("event", event.name());
                    writer.addAttribute("script", env.getScript(script).getName());
                    for (FxScriptMappingEntry sme : env.getScriptMapping(script).getMappedTypes()) {
                        if (sme.getId() == type.getId()
                                || ArrayUtils.contains(sme.getDerivedIds(), type.getId())) {
                            writer.addAttribute("active", String.valueOf(sme.isActive()));
                            writer.addAttribute("derivedUsage", String.valueOf(sme.isDerivedUsage()));
                            writer.addAttribute("derived", String.valueOf(sme.getId() != type.getId()));
                            if (sme.getId() != type.getId())
                                writer.addAttribute("baseType", env.getType(sme.getId()).getName());
                            break;
                        }
                    }
                    writer.endNode();
                }
            }
            writer.endNode();
        }

        writer.startNode("assignments");
        for (FxAssignment as : type.getConnectedAssignments("/")) {
            if (as.isSystemInternal())
                continue;
            ctx.convertAnother(as);
        }
        writer.endNode();

    } catch (Exception e) {
        throw new FxConversionException(e, "ex.conversion.type.error", type.getName(), e.getMessage())
                .asRuntimeException();
    }
}

From source file:info.magnolia.templating.jsp.taglib.SearchResultSnippetTag.java

/**
 * Extract a collection of snippets from any paragraph in the given page.
 * @return a collection of Strings./*from ww  w.ja  v a 2s.c o m*/
 * @todo avoid overlapping snippets (use regexp insted of simple indexOfs)
 * @todo only extract snippets from user-configured properties
 * @todo abbreviate on whitespace and puntuation, detect start of sentences
 * @todo replace ampersand in regexp
 * @todo break methods and write junits
 */
public Collection getSnippets() {

    log.debug("collecting snippets");

    Collection snippets = new ArrayList();
    String[] searchTerms = StringUtils.split(this.query);

    try {
        Iterator<Node> iterator = NodeUtil.getNodes(this.page, NodeTypes.ContentNode.NAME).iterator();

        outer: while (iterator.hasNext()) {
            Node paragraphCollection = iterator.next();

            Iterator<Node> parIterator = NodeUtil.getNodes(paragraphCollection, NodeTypes.ContentNode.NAME)
                    .iterator();
            while (parIterator.hasNext()) {
                Node paragraph = parIterator.next();

                log.debug("Iterating on paragraph {}", paragraph);

                Iterator dataIterator = paragraph.getProperties();

                while (dataIterator.hasNext()) {
                    Property property = (Property) dataIterator.next();
                    if (property.getType() != PropertyType.BINARY) {

                        String resultString = property.getString();

                        log.debug("Iterating on property {}", property.getName());
                        log.debug("Property value is {}", resultString);

                        // a quick and buggy way to avoid configuration properties, we should allow the user to
                        // configure a list of nodeData to search for...
                        if (resultString.length() < 20) {
                            continue;
                        }

                        for (int j = 0; j < searchTerms.length; j++) {
                            String searchTerm = StringUtils.lowerCase(searchTerms[j]);

                            // exclude keywords and words with less than 2 chars
                            if (!ArrayUtils.contains(new String[] { "and", "or" }, searchTerm)
                                    && searchTerm.length() > 2) {

                                log.debug("Looking for search term [{}] in [{}]", searchTerm, resultString);

                                // first check, avoid using heavy string replaceAll operations if the search term is not
                                // there
                                if (!StringUtils.contains(resultString.toLowerCase(), searchTerm)) {
                                    continue;
                                }

                                // strips out html tags using a regexp
                                resultString = stripHtmlTags(resultString);

                                // only get first matching keyword
                                int pos = resultString.toLowerCase().indexOf(searchTerm);
                                if (pos > -1) {

                                    int posEnd = pos + searchTerm.length();
                                    int from = (pos - chars / 2);
                                    if (from < 0) {
                                        from = 0;
                                    }

                                    int to = from + chars;
                                    if (to > resultString.length()) {
                                        to = resultString.length();
                                    }

                                    StringBuffer snippet = new StringBuffer();

                                    snippet.append(StringUtils.substring(resultString, from, pos));
                                    snippet.append("<strong>");
                                    snippet.append(StringUtils.substring(resultString, pos, posEnd));
                                    snippet.append("</strong>");
                                    snippet.append(StringUtils.substring(resultString, posEnd, to));

                                    if (from > 0) {
                                        snippet.insert(0, "... ");
                                    }
                                    if (to < resultString.length()) {
                                        snippet.append("... ");
                                    }

                                    log.debug("Search term found, adding snippet {}", snippet);

                                    snippets.add(snippet);
                                    if (snippets.size() >= this.maxSnippets) {

                                        log.debug("Maximum number of snippets ({}) reached, exiting",
                                                Integer.toString(this.maxSnippets));

                                        break outer;
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
        return snippets;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return null;
    }
}

From source file:com.adobe.acs.commons.contentfinder.querybuilder.impl.viewhandler.GQLToQueryBuilderConverter.java

public static Map<String, String> addProperty(final SlingHttpServletRequest request, Map<String, String> map,
        final String requestKey, final int count) {
    if (!ArrayUtils.contains(ContentFinderConstants.PROPERTY_BLACKLIST, requestKey)) {
        map = putProperty(request, map, requestKey, JcrPropertyPredicateEvaluator.PROPERTY,
                (GROUP_PROPERTY_USERDEFINED + count), true);
    } else {// w  w  w .  j av  a  2 s . c  o m
        log.debug("Rejecting property [ {} ] due to blacklist match", requestKey);
    }
    return map;
}

From source file:com.ecyrd.jspwiki.auth.UserManagerTest.java

public void testSetRenamedUserProfile() throws Exception {
    // First, count the number of users, groups, and pages
    int oldUserCount = m_db.getWikiNames().length;
    GroupManager groupManager = m_engine.getGroupManager();
    PageManager pageManager = m_engine.getPageManager();
    AuthorizationManager authManager = m_engine.getAuthorizationManager();
    int oldGroupCount = groupManager.getRoles().length;
    int oldPageCount = pageManager.getTotalPageCount();

    // Setup Step 1: create a new user with random name
    WikiSession session = m_engine.guestSession();
    long now = System.currentTimeMillis();
    String oldLogin = "TestLogin" + now;
    String oldName = "Test User " + now;
    String newLogin = "RenamedLogin" + now;
    String newName = "Renamed User " + now;
    UserProfile profile = m_db.newProfile();
    profile.setEmail("testuser@testville.com");
    profile.setLoginName(oldLogin);//from   w  ww.j  a  v  a 2 s . c o  m
    profile.setFullname(oldName);
    profile.setPassword("password");
    m_mgr.setUserProfile(session, profile);

    // 1a. Make sure the profile saved successfully and that we're logged in
    profile = m_mgr.getUserProfile(session);
    assertEquals(oldLogin, profile.getLoginName());
    assertEquals(oldName, profile.getFullname());
    assertEquals(oldUserCount + 1, m_db.getWikiNames().length);
    assertTrue(session.isAuthenticated());

    // Setup Step 2: create a new group with our test user in it
    Group group = groupManager.parseGroup(m_groupName,
            "Alice \n Bob \n Charlie \n " + oldLogin + "\n" + oldName, true);
    groupManager.setGroup(session, group);

    // 2a. Make sure the group is created with the user in it, and the role is added to the Subject
    assertEquals(oldGroupCount + 1, groupManager.getRoles().length);
    assertTrue(group.isMember(new WikiPrincipal(oldLogin)));
    assertTrue(group.isMember(new WikiPrincipal(oldName)));
    assertFalse(group.isMember(new WikiPrincipal(newLogin)));
    assertFalse(group.isMember(new WikiPrincipal(newName)));
    assertTrue(groupManager.isUserInRole(session, group.getPrincipal()));

    // Setup Step 3: create a new page with our test user in the ACL
    String pageName = "TestPage" + now;
    m_engine.saveText(pageName,
            "Test text. [{ALLOW view " + oldName + ", " + oldLogin + ", Alice}] More text.");

    // 3a. Make sure the page got saved, and that ONLY our test user has permission to read it.
    WikiPage p = m_engine.getPage(pageName);
    assertEquals(oldPageCount + 1, pageManager.getTotalPageCount());
    assertNotNull(p.getAcl().getEntry(new WikiPrincipal(oldLogin)));
    assertNotNull(p.getAcl().getEntry(new WikiPrincipal(oldName)));
    assertNull(p.getAcl().getEntry(new WikiPrincipal(newLogin)));
    assertNull(p.getAcl().getEntry(new WikiPrincipal(newName)));
    assertTrue("Test User view page",
            authManager.checkPermission(session, PermissionFactory.getPagePermission(p, "view")));
    WikiSession bobSession = WikiSessionTest.authenticatedSession(m_engine, Users.BOB, Users.BOB_PASS);
    assertFalse("Bob !view page",
            authManager.checkPermission(bobSession, PermissionFactory.getPagePermission(p, "view")));

    // Setup Step 4: change the user name in the profile and see what happens
    profile = m_db.newProfile();
    profile.setEmail("testuser@testville.com");
    profile.setLoginName(oldLogin);
    profile.setFullname(newName);
    profile.setPassword("password");
    m_mgr.setUserProfile(session, profile);

    // Test 1: the wiki session should have the new wiki name in Subject
    Principal[] principals = session.getPrincipals();
    assertTrue(ArrayUtils.contains(principals, new WikiPrincipal(oldLogin)));
    assertFalse(ArrayUtils.contains(principals, new WikiPrincipal(oldName)));
    assertFalse(ArrayUtils.contains(principals, new WikiPrincipal(newLogin)));
    assertTrue(ArrayUtils.contains(principals, new WikiPrincipal(newName)));

    // Test 2: our group should not contain the old name OR login name any more
    // (the full name is always used)
    group = groupManager.getGroup(m_groupName);
    assertFalse(group.isMember(new WikiPrincipal(oldLogin)));
    assertFalse(group.isMember(new WikiPrincipal(oldName)));
    assertFalse(group.isMember(new WikiPrincipal(newLogin)));
    assertTrue(group.isMember(new WikiPrincipal(newName)));

    // Test 3: our page should not contain the old wiki name OR login name
    // in the ACL any more (the full name is always used)
    p = m_engine.getPage(pageName);
    assertNull(p.getAcl().getEntry(new WikiPrincipal(oldLogin)));
    assertNull(p.getAcl().getEntry(new WikiPrincipal(oldName)));
    assertNull(p.getAcl().getEntry(new WikiPrincipal(newLogin)));
    assertNotNull(p.getAcl().getEntry(new WikiPrincipal(newName)));
    assertTrue("Test User view page",
            authManager.checkPermission(session, PermissionFactory.getPagePermission(p, "view")));
    assertFalse("Bob !view page",
            authManager.checkPermission(bobSession, PermissionFactory.getPagePermission(p, "view")));

    // Test 4: our page text should have been re-written
    // (The new full name should be in the ACL, but the login name should have been removed)
    String expectedText = "[{ALLOW view Alice," + newName + "}]\nTest text.  More text.\r\n";
    String actualText = m_engine.getText(pageName);
    assertEquals(expectedText, actualText);

    // Remove our test page
    m_engine.deletePage(pageName);

    // Setup Step 6: re-create the group with our old test user names in it
    group = groupManager.parseGroup(m_groupName, "Alice \n Bob \n Charlie \n " + oldLogin + "\n" + oldName,
            true);
    groupManager.setGroup(session, group);

    // Setup Step 7: Save a new page with the old login/wiki names in the ACL again
    // The test user should still be able to see the page (because the login name matches...)
    pageName = "TestPage2" + now;
    m_engine.saveText(pageName,
            "More test text. [{ALLOW view " + oldName + ", " + oldLogin + ", Alice}] More text.");
    p = m_engine.getPage(pageName);
    assertEquals(oldPageCount + 1, pageManager.getTotalPageCount());
    assertNotNull(p.getAcl().getEntry(new WikiPrincipal(oldLogin)));
    assertNotNull(p.getAcl().getEntry(new WikiPrincipal(oldName)));
    assertNull(p.getAcl().getEntry(new WikiPrincipal(newLogin)));
    assertNull(p.getAcl().getEntry(new WikiPrincipal(newName)));
    assertTrue("Test User view page",
            authManager.checkPermission(session, PermissionFactory.getPagePermission(p, "view")));
    assertFalse("Bob !view page",
            authManager.checkPermission(bobSession, PermissionFactory.getPagePermission(p, "view")));

    // Setup Step 8: re-save the profile with the new login name
    profile = m_db.newProfile();
    profile.setEmail("testuser@testville.com");
    profile.setLoginName(newLogin);
    profile.setFullname(oldName);
    profile.setPassword("password");
    m_mgr.setUserProfile(session, profile);

    // Test 5: the wiki session should have the new login name in Subject
    principals = session.getPrincipals();
    assertFalse(ArrayUtils.contains(principals, new WikiPrincipal(oldLogin)));
    assertTrue(ArrayUtils.contains(principals, new WikiPrincipal(oldName)));
    assertTrue(ArrayUtils.contains(principals, new WikiPrincipal(newLogin)));
    assertFalse(ArrayUtils.contains(principals, new WikiPrincipal(newName)));

    // Test 6: our group should not contain the old name OR login name any more
    // (the full name is always used)
    group = groupManager.getGroup(m_groupName);
    assertFalse(group.isMember(new WikiPrincipal(oldLogin)));
    assertTrue(group.isMember(new WikiPrincipal(oldName)));
    assertFalse(group.isMember(new WikiPrincipal(newLogin)));
    assertFalse(group.isMember(new WikiPrincipal(newName)));

    // Test 7: our page should not contain the old wiki name OR login name
    // in the ACL any more (the full name is always used)
    p = m_engine.getPage(pageName);
    assertNull(p.getAcl().getEntry(new WikiPrincipal(oldLogin)));
    assertNotNull(p.getAcl().getEntry(new WikiPrincipal(oldName)));
    assertNull(p.getAcl().getEntry(new WikiPrincipal(newLogin)));
    assertNull(p.getAcl().getEntry(new WikiPrincipal(newName)));
    assertTrue("Test User view page",
            authManager.checkPermission(session, PermissionFactory.getPagePermission(p, "view")));
    assertFalse("Bob !view page",
            authManager.checkPermission(bobSession, PermissionFactory.getPagePermission(p, "view")));

    // Test 8: our page text should have been re-written
    // (The new full name should be in the ACL, but the login name should have been removed)
    expectedText = "[{ALLOW view Alice," + oldName + "}]\nMore test text.  More text.\r\n";
    actualText = m_engine.getText(pageName);
    assertEquals(expectedText, actualText);

    // CLEANUP: delete the profile; user and page; should be back to old counts
    m_db.deleteByLoginName(newLogin);
    assertEquals(oldUserCount, m_db.getWikiNames().length);

    groupManager.removeGroup(group.getName());
    assertEquals(oldGroupCount, groupManager.getRoles().length);

    m_engine.deletePage(pageName);
    assertEquals(oldPageCount, pageManager.getTotalPageCount());
}

From source file:application.ReviewDocumentIndexer.java

private void setArgs(String[] args) throws RuntimeException {
    // Parse and process command line arguments
    for (String arg : args) {
        arg = arg.toLowerCase();/*from  www  . j ava 2s. co  m*/
    }

    if (args.length == 1 || ArrayUtils.contains(args, "--help"))
        throw new RuntimeException("Command line syntax error");

    if (ArrayUtils.contains(args, "--new")) {
        min_reviewid = 0;
        new_index = true;
    } else if (ArrayUtils.contains(args, "--resume")) {
        try {
            restoreState();
            min_reviewid = theReviewId.get();
        } catch (IOException e) {
            AppLogger.error.log(Level.SEVERE,
                    "Cannot restore indexer state. Some files are missing or are unreadable.");
        }
    } else if (ArrayUtils.contains(args, "--update")) {
        try {
            restoreState();
            min_reviewid = 0;
        } catch (IOException e) {
            AppLogger.error.log(Level.SEVERE,
                    "Cannot restore indexer state. Some files are missing or are unreadable.");
        }
    } else if (ArrayUtils.contains(args, "--restore")) {
        try {
            restoreIndex();
            restoreState();
            min_reviewid = theReviewId.get();
        } catch (IOException e) {
            AppLogger.error.log(Level.SEVERE,
                    "Cannot restore index from backup. Some files are missing or are unreadable.");
        }
    } else
        throw new RuntimeException("Command line syntax error");

    int pos = -1;
    try {
        if ((pos = ArrayUtils.indexOf(args, "--stop-after")) != ArrayUtils.INDEX_NOT_FOUND) {
            stop_after = min_reviewid + Integer.parseInt(args[pos + 1]);
        }
        if ((pos = ArrayUtils.indexOf(args, "--pause-every")) != ArrayUtils.INDEX_NOT_FOUND) {
            pause_every = Integer.parseInt(args[pos + 1]);
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        throw new RuntimeException("Command line syntax error");
    }
}

From source file:com.htmlhifive.tools.rhino.comment.js.JSDocCommentNodeParser.java

private JSTagNode resolveTagNode(JSTag currentTag) {

    if (ArrayUtils.contains(TagType.NO_PART_TAG.getJsTag(), currentTag)) {
        return new JSNoPartTagNode(currentTag);
    } else if (ArrayUtils.contains(TagType.SINGLE_PART_TAG.getJsTag(), currentTag)) {
        return new JSSinglePartTagNode(currentTag);
    } else if (ArrayUtils.contains(TagType.OTHER_PARAM_TAG.getJsTag(), currentTag)) {
        switch (currentTag) {
        case PARAM:
        case PROPERTY:
            return new JSTypeNamePartNode(currentTag);

        case THROWS:
        case RETURNS:
            return new JSTypePartNode(currentTag);
        default:/*  ww  w. j  a v a 2 s.  c  o  m*/
            break;
        }
        // ??SinglePartTag?
        return new JSSinglePartTagNode(currentTag);
    }
    return null;
}

From source file:es.tena.foundation.util.POIUtil.java

/**
 * Corrige algunos problemas con los caracteres invlidos al generar
 * ficheros grandes con el SpreadSheetWriter de POI
 *
 * @param valor/*w  ww.  j  a  va2s  .  co m*/
 * @return la ristra corregida escapando carateres no validos para un xml
 * asi como eliminando aquellos que no estn en el juego de caracteres
 */
public static String fixPOICellValue(String valor, String encoding) {
    try {
        //Poi para los ficheros xml se hace un lio con los &
        // y los considera entidades, para escaparlos deberia bastar con && pero no es asi

        byte[] bs = valor.getBytes(encoding);

        StringBuilder buff = new StringBuilder();
        if (contieneCaracteresNoPermitidos(bs)) {
            for (int i = 0; i < bs.length; i++) {
                byte c = bs[i];
                //                    Logger.getLogger(Utils.class.getName()).log(Level.INFO, "\t\t byte: [{0}]-{1}-{2}-\n", new Object[]{i, (char)c , c});
                // substituyo caracteres extraos
                if (c == 24 || c == 127) {
                    c = 32;// los espacios extraos por el nbsp
                }
                // si no es un caracter no permitido lo aadimos
                if (!ArrayUtils.contains(bytesNotAllowed, c)) {
                    buff.append((char) c);
                } else {
                    Logger.getLogger(POIUtil.class.getName()).log(Level.INFO,
                            "\t\t ESCAPADO de ''{3}'' byte : [{0}]-{1}-''{2}''\n",
                            new Object[] { i, c, (char) c, valor });
                }
            }
            valor = buff.toString();
        } else {
            try {
                StringValidator.checkInString(valor, StringUtil.notNumbers + StringUtil.numbers + " " + "@"
                        + "\"" + "" + "\r" + "\n" + "\t");
            } catch (RuntimeException e) {
                Logger.getLogger(POIUtil.class.getName()).log(Level.FINE, "\t\t SOSPECHOSO [{0}]:{1}\n",
                        new Object[] { valor, e.getMessage() });
            }
        }
        // Escapamos los caracteres conflictivos para que sean validos para el xml
        valor = StringEscapeUtils.escapeXml(valor);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(POIUtil.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NullPointerException e) {
    }
    return valor;
}