Example usage for com.google.common.base Splitter split

List of usage examples for com.google.common.base Splitter split

Introduction

In this page you can find the example usage for com.google.common.base Splitter split.

Prototype

@CheckReturnValue
public Iterable<String> split(final CharSequence sequence) 

Source Link

Document

Splits sequence into string components and makes them available through an Iterator , which may be lazily evaluated.

Usage

From source file:org.apache.gobblin.qualitychecker.row.RowLevelPolicyCheckerBuilder.java

@SuppressWarnings("unchecked")
private List<RowLevelPolicy> createPolicyList() throws Exception {
    List<RowLevelPolicy> list = new ArrayList<>();
    Splitter splitter = Splitter.on(",").omitEmptyStrings().trimResults();
    String rowLevelPoliciesKey = ForkOperatorUtils
            .getPropertyNameForBranch(ConfigurationKeys.ROW_LEVEL_POLICY_LIST, this.index);
    String rowLevelPolicyTypesKey = ForkOperatorUtils
            .getPropertyNameForBranch(ConfigurationKeys.ROW_LEVEL_POLICY_LIST_TYPE, this.index);
    if (this.state.contains(rowLevelPoliciesKey) && this.state.contains(rowLevelPolicyTypesKey)) {
        List<String> policies = Lists.newArrayList(splitter.split(this.state.getProp(rowLevelPoliciesKey)));
        List<String> types = Lists.newArrayList(splitter.split(this.state.getProp(rowLevelPolicyTypesKey)));
        if (policies.size() != types.size()) {
            throw new Exception("Row Policies list and Row Policies list type are not the same length");
        }//ww  w  . j  av a2  s.  co  m
        for (int i = 0; i < policies.size(); i++) {
            try {
                Class<? extends RowLevelPolicy> policyClass = (Class<? extends RowLevelPolicy>) Class
                        .forName(policies.get(i));
                Constructor<? extends RowLevelPolicy> policyConstructor = policyClass
                        .getConstructor(State.class, RowLevelPolicy.Type.class);
                RowLevelPolicy policy = policyConstructor.newInstance(this.state,
                        RowLevelPolicy.Type.valueOf(types.get(i)));
                list.add(policy);
            } catch (Exception e) {
                LOG.error(rowLevelPoliciesKey + " contains a class " + policies.get(i)
                        + " which doesn't extend RowLevelPolicy.", e);
                throw e;
            }
        }
    }
    return list;
}

From source file:edu.umich.robot.soar.SoarAgent.java

public SoarAgent(Agent agent, RobotOutput output, WallClock clock, Config propc) {
    this.agent = agent;
    this.output = output;
    this.clock = clock;
    this.waypoints = new WaypointManager(getName());

    properties.setProvider(AgentProperties.LENGTH_UNIT, lengthUnit);
    properties.setProvider(AgentProperties.LINEAR_SPEED_UNIT, linSpeedUnit);
    properties.setProvider(AgentProperties.ANGULAR_SPEED_UNIT, angSpeedUnit);
    properties.setProvider(AgentProperties.ANGLE_UNIT, angleUnit);
    properties.setProvider(AgentProperties.ANGLE_RESOLUTION, angleResolution);
    properties.setProvider(AgentProperties.TRANSLATION, translation);
    properties.setProvider(AgentProperties.OBJECT_LINGER_SECONDS, lingerSeconds);

    if (propc != null)
        setDefaults(propc);/*from  w ww  .  java  2 s. c o m*/

    properties.addListener(AgentProperties.LEARN, new PropertyListener<LearnSetting>() {
        public void propertyChanged(PropertyChangeEvent<LearnSetting> event) {
            SoarAgent.this.agent.ExecuteCommandLine(event.getNewValue().toCommandLine());
        }
    });
    properties.setProvider(AgentProperties.LEARN, learn);

    properties.addListener(AgentProperties.EPMEM_LEARNING, new PropertyListener<Boolean>() {
        public void propertyChanged(PropertyChangeEvent<Boolean> event) {
            if (event.getNewValue()) {
                SoarAgent.this.agent.ExecuteCommandLine("epmem -s learning on");
                SoarAgent.this.agent.ExecuteCommandLine("epmem -s timers three");
            } else {
                SoarAgent.this.agent.ExecuteCommandLine("epmem -s learning off");
            }
        }
    });
    properties.setProvider(AgentProperties.EPMEM_LEARNING, epmemLearn);

    properties.addListener(AgentProperties.SMEM_LEARNING, new PropertyListener<Boolean>() {
        public void propertyChanged(PropertyChangeEvent<Boolean> event) {
            if (event.getNewValue()) {
                SoarAgent.this.agent.ExecuteCommandLine("smem -s learning on");
                SoarAgent.this.agent.ExecuteCommandLine("smem -s timers three");
            } else {
                SoarAgent.this.agent.ExecuteCommandLine("smem -s learning off");
            }
        }
    });
    properties.setProvider(AgentProperties.SMEM_LEARNING, smemLearn);

    // because epmem exclusions are toggled, we need to turn on all the defaults 
    // except the two that are on by default (epmem, smem)
    for (String s : epmemExclusions.get()) {
        if (s.equals("epmem") || s.equals("smem"))
            continue;
        agent.ExecuteCommandLine("epmem -s exclusions " + s);
    }

    // This whole step verifies the setting by asking the agent. It isn't necessary but is here for a sanity check.
    // BUGBUG: agents can change this behind our back (in firstload). It needs to be updated before use.
    Splitter splitter = Splitter.on(", ").trimResults();
    List<String> exclList = Lists.newArrayList(splitter.split(agent.ExecuteCommandLine("epmem -g exclusions")));
    epmemExclusions.set(exclList.toArray(new String[exclList.size()]));
    logger.debug("Initial epmem exclusions: " + Arrays.toString(epmemExclusions.get()));

    // Setting provider before adding listener so that event doesn't fire.
    properties.setProvider(AgentProperties.EPMEM_EXCLUSIONS, epmemExclusions);
    properties.addListener(AgentProperties.EPMEM_EXCLUSIONS, new PropertyListener<String[]>() {
        public void propertyChanged(PropertyChangeEvent<String[]> event) {
            // removes old values
            for (String s : event.getOldValue()) {
                logger.debug("epmem -s exclusions " + s);
                SoarAgent.this.agent.ExecuteCommandLine("epmem -s exclusions " + s);
            }

            for (String s : event.getNewValue()) {
                logger.debug("epmem -s exclusions " + s);
                SoarAgent.this.agent.ExecuteCommandLine("epmem -s exclusions " + s);
            }

            logger.debug("exclusions after update: "
                    + SoarAgent.this.agent.ExecuteCommandLine("epmem -g exclusions").trim());
        }
    });

    addSpProperty(AgentProperties.DEFAULT_STORAGE_AREA_ID, defaultStorageAreaId);
    addSpProperty(AgentProperties.AREAS_HELD_IN, areasHeldIn);
    addSpProperty(AgentProperties.OBJECTS_HELD_IN, objectsHeldIn);
    addSpProperty(AgentProperties.LOOK_AHEAD_PLANNING, lookAheadPlanning);
    addSpProperty(AgentProperties.SEARCH_CONTROL_GO_TO_GATEWAY, searchControlGoToGateway);
    addSpProperty(AgentProperties.DELETE_OLD_AREAS, deleteOldAreas);

    properties.addListener(AgentProperties.MISSION, new PropertyListener<Mission>() {
        public void propertyChanged(PropertyChangeEvent<Mission> event) {
            SoarAgent.this.agent
                    .ExecuteCommandLine(makeSpParam(event.getKey().toString(), event.getNewValue()));
        }
    });
    properties.setProvider(AgentProperties.MISSION, mission);

    properties.addListener(AgentProperties.MISC_COMMANDS, new PropertyListener<String[]>() {
        public void propertyChanged(PropertyChangeEvent<String[]> event) {
            for (String s : event.getNewValue()) {
                logger.debug(s);
                SoarAgent.this.agent.ExecuteCommandLine(s);
            }
        }
    });
    properties.setProvider(AgentProperties.MISC_COMMANDS, miscCommands);
}

From source file:ru.codeinside.adm.parser.EmployeeFixtureParser.java

public void loadFixtures(InputStream is, EmployeeFixtureParser.PersistenceCallback callback)
        throws IOException {
    final Splitter propertySplitter = Splitter.on(';');
    final BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
    String line;/*from  ww w .  ja va2  s  .c  o m*/
    int lineNumber = 0;
    while ((line = reader.readLine()) != null) {
        lineNumber++;
        int level = startIndex(line);
        if (line.startsWith("#") || level < 0) {
            continue;
        }
        final ArrayList<String> props = Lists.newArrayList(propertySplitter.split(line.substring(level)));
        final String name = StringUtils.trimToNull(props.get(0));
        if (name == null) {
            if (props.size() == 1) {
                continue;
            }
            throw new IllegalStateException(" ?( ?:" + lineNumber + ")");
        } else if (name.length() >= 255) {
            throw new IllegalStateException(
                    "     255 ? (?: "
                            + lineNumber + ")");
        }
        final boolean isOrg = props.size() <= 2;
        Row parent = getParentRow(level);
        final Set<String> groups = parseGroups(props, getGroupPropertyIndex(isOrg));
        if (isOrg) {
            long orgId = callback.onOrganizationComplete(name, groups, parent != null ? parent.id : null);
            stack.addLast(new Row(level, orgId));
        }
        if (!isOrg && parent != null) {
            String pwd = defaultIfEmpty(trimToNull(props.get(2)), null);
            Set<Role> roles = parseRoles(groupSplitter, lineNumber, props.get(3));
            callback.onUserComplete(StringUtils.trim(props.get(1)), pwd, name, parent.id, roles, groups);
        }
        if (!isOrg && parent == null) {
            throw new IllegalStateException(
                    "  (?:" + lineNumber + ").");
        }
    }
}

From source file:org.apache.phoenix.expression.function.RegexpSplitFunction.java

private boolean split(Tuple tuple, ImmutableBytesWritable ptr, String sourceStr) {
    Splitter splitter = initializedSplitter;
    if (splitter == null) {
        Expression patternExpression = children.get(1);
        if (!patternExpression.evaluate(tuple, ptr)) {
            return false;
        }/*from   w  ww .  j a va2s  .c o  m*/
        if (ptr.getLength() == 0) {
            return true; // ptr is already set to null
        }

        String patternStr = (String) PVarchar.INSTANCE.toObject(ptr, patternExpression.getSortOrder());
        splitter = Splitter.onPattern(patternStr);
    }

    List<String> splitStrings = Lists.newArrayList(splitter.split(sourceStr));
    PhoenixArray splitArray = new PhoenixArray(PVarchar.INSTANCE, splitStrings.toArray());
    ptr.set(PVarcharArray.INSTANCE.toBytes(splitArray));
    return true;
}

From source file:org.apache.sentry.provider.file.SimplePolicyEngine.java

private ImmutableSetMultimap<String, String> parsePermissions(@Nullable String database,
        Ini.Section rolesSection, Ini.Section groupsSection) {
    ImmutableSetMultimap.Builder<String, String> resultBuilder = ImmutableSetMultimap.builder();
    Multimap<String, String> roleNameToPrivilegeMap = HashMultimap.create();
    List<? extends RoleValidator> validators = Lists.newArrayList(new ServersAllIsInvalid(),
            new DatabaseMustMatch(), new DatabaseRequiredInRole(), new ServerNameMustMatch(serverName));
    for (Map.Entry<String, String> entry : rolesSection.entrySet()) {
        String roleName = Strings.nullToEmpty(entry.getKey()).trim();
        String roleValue = Strings.nullToEmpty(entry.getValue()).trim();
        boolean invalidConfiguration = false;
        if (roleName.isEmpty()) {
            LOGGER.warn("Empty role name encountered in {}", resourcePath);
            invalidConfiguration = true;
        }//from   w  ww .  ja  v  a  2 s  . com
        if (roleValue.isEmpty()) {
            LOGGER.warn("Empty role value encountered in {}", resourcePath);
            invalidConfiguration = true;
        }
        if (roleNameToPrivilegeMap.containsKey(roleName)) {
            LOGGER.warn("Role {} defined twice in {}", roleName, resourcePath);
        }
        Set<String> roles = PermissionUtils.toPermissionStrings(roleValue);
        if (!invalidConfiguration && roles != null) {
            for (String role : roles) {
                for (RoleValidator validator : validators) {
                    validator.validate(database, role.trim());
                }
            }
            roleNameToPrivilegeMap.putAll(roleName, roles);
        }
    }
    Splitter roleSplitter = ROLE_SPLITTER.omitEmptyStrings().trimResults();
    for (Map.Entry<String, String> entry : groupsSection.entrySet()) {
        String groupName = Strings.nullToEmpty(entry.getKey()).trim();
        String groupPrivileges = Strings.nullToEmpty(entry.getValue()).trim();
        Collection<String> resolvedGroupPrivileges = Sets.newHashSet();
        for (String roleName : roleSplitter.split(groupPrivileges)) {
            if (roleNameToPrivilegeMap.containsKey(roleName)) {
                resolvedGroupPrivileges.addAll(roleNameToPrivilegeMap.get(roleName));
            } else {
                LOGGER.warn("Role {} for group {} does not exist in privileges section in {}",
                        new Object[] { roleName, groupName, resourcePath });
            }
        }
        resultBuilder.putAll(groupName, resolvedGroupPrivileges);
    }
    return resultBuilder.build();
}

From source file:org.dcache.nfs.v4.client.CompoundBuilder.java

public CompoundBuilder withLookup(String path) {
    final Splitter splitter = Splitter.on('/').omitEmptyStrings();

    for (String s : splitter.split(path)) {
        if ("..".equals(s)) {
            withLookupp();//from w w  w.j a v  a  2  s.c  o m
            continue;
        }
        nfs_argop4 op = new nfs_argop4();
        op.argop = nfs_opnum4.OP_LOOKUP;
        op.oplookup = new LOOKUP4args();

        op.oplookup.objname = new component4(s);
        ops.add(op);
    }

    return this;
}

From source file:buildcraft.BuildCraftTransport.java

@IMCCallback
public void processIMCRequests(FMLInterModComms.IMCEvent event) {
    Splitter splitter = Splitter.on("@").trimResults();
    for (IMCMessage m : event.getMessages()) {
        if ("add-facade".equals(m.key)) {
            String[] array = Iterables.toArray(splitter.split(m.getStringValue()), String.class);
            if (array.length != 2) {
                Logger.getLogger("Buildcraft").log(Level.INFO,
                        String.format("Received an invalid add-facade request %s from mod %s",
                                m.getStringValue(), m.getSender()));
                continue;
            }/* w  w  w . j a v a2s  .c  om*/
            Integer blId = Ints.tryParse(array[0]);
            Integer metaId = Ints.tryParse(array[1]);
            if (blId == null || metaId == null) {
                Logger.getLogger("Buildcraft").log(Level.INFO,
                        String.format("Received an invalid add-facade request %s from mod %s",
                                m.getStringValue(), m.getSender()));
                continue;
            }
            ItemFacade.addFacade(new ItemStack(blId, 1, metaId));
        }
    }
}

From source file:org.gbif.registry.metadata.parse.DatasetWrapper.java

/**
 * Adds a comma or semicolon concatenated keyword string as keyword collection.
 *//*ww  w .  j a va 2 s.c  o m*/
public void addSubjects(String subjects) {
    Splitter keywordSplitter = Splitter.on(Pattern.compile("[,;]")).trimResults().omitEmptyStrings();
    if (!Strings.isNullOrEmpty(subjects)) {
        KeywordCollection collection = new KeywordCollection();
        for (String keyword : keywordSplitter.split(subjects)) {
            collection.addKeyword(keyword);
        }
        target.getKeywordCollections().add(collection);
    }
}

From source file:org.dcache.nfs.vfs.PseudoFs.java

private void pathToPseudoFs(final PseudoFsNode root, Set<PseudoFsNode> all, FsExport e) {

    PseudoFsNode parent = root;// w  ww  . j av a 2s.  c om
    String path = e.getPath();

    if (e.getPath().equals("/")) {
        root.addExport(e);
        return;
    }

    Splitter splitter = Splitter.on('/').omitEmptyStrings();
    Set<PseudoFsNode> pathNodes = new HashSet<>();

    for (String s : splitter.split(path)) {
        try {
            PseudoFsNode node = parent.getChild(s);
            if (node == null) {
                node = new PseudoFsNode(realToPseudo(_inner.lookup(parent.id(), s)));
                parent.addChild(s, node);
                pathNodes.add(node);
            }
            parent = node;
        } catch (IOException ef) {
            return;
        }
    }

    all.addAll(pathNodes);
    parent.setId(pseudoIdToReal(parent.id(), e.getIndex()));
    parent.addExport(e);
}

From source file:org.apache.sentry.provider.file.SimpleFileProviderBackend.java

private void parsePrivileges(@Nullable String database, Ini.Section rolesSection, Ini.Section groupsSection,
        List<? extends PrivilegeValidator> validators, Path policyPath,
        Table<String, String, Set<String>> groupRolePrivilegeTable) {
    Multimap<String, String> roleNameToPrivilegeMap = HashMultimap.create();
    for (Map.Entry<String, String> entry : rolesSection.entrySet()) {
        String roleName = stringInterner.intern(Strings.nullToEmpty(entry.getKey()).trim());
        String roleValue = Strings.nullToEmpty(entry.getValue()).trim();
        boolean invalidConfiguration = false;
        if (roleName.isEmpty()) {
            String errMsg = String.format("Empty role name encountered in %s", policyPath);
            LOGGER.warn(errMsg);/*from w ww . j av a  2  s .  c o m*/
            configErrors.add(errMsg);
            invalidConfiguration = true;
        }
        if (roleValue.isEmpty()) {
            String errMsg = String.format("Empty role value encountered in %s", policyPath);
            LOGGER.warn(errMsg);
            configErrors.add(errMsg);
            invalidConfiguration = true;
        }
        if (roleNameToPrivilegeMap.containsKey(roleName)) {
            String warnMsg = String.format("Role %s defined twice in %s", roleName, policyPath);
            LOGGER.warn(warnMsg);
            configWarnings.add(warnMsg);
        }
        Set<String> privileges = PrivilegeUtils.toPrivilegeStrings(roleValue);
        if (!invalidConfiguration && privileges != null) {
            Set<String> internedPrivileges = Sets.newHashSet();
            for (String privilege : privileges) {
                for (PrivilegeValidator validator : validators) {
                    validator.validate(new PrivilegeValidatorContext(database, privilege.trim()));
                }
                internedPrivileges.add(stringInterner.intern(privilege));
            }
            roleNameToPrivilegeMap.putAll(roleName, internedPrivileges);
        }
    }
    Splitter roleSplitter = ROLE_SPLITTER.omitEmptyStrings().trimResults();
    for (Map.Entry<String, String> entry : groupsSection.entrySet()) {
        String groupName = stringInterner.intern(Strings.nullToEmpty(entry.getKey()).trim());
        String groupPrivileges = Strings.nullToEmpty(entry.getValue()).trim();
        for (String roleName : roleSplitter.split(groupPrivileges)) {
            roleName = stringInterner.intern(roleName);
            if (roleNameToPrivilegeMap.containsKey(roleName)) {
                Set<String> privileges = groupRolePrivilegeTable.get(groupName, roleName);
                if (privileges == null) {
                    privileges = new HashSet<String>();
                    groupRolePrivilegeTable.put(groupName, roleName, privileges);
                }
                privileges.addAll(roleNameToPrivilegeMap.get(roleName));
            } else {
                String warnMsg = String.format(
                        "Role %s for group %s does not exist in privileges section in %s", roleName, groupName,
                        policyPath);
                LOGGER.warn(warnMsg);
                configWarnings.add(warnMsg);
            }
        }
    }
}