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

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

Introduction

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

Prototype

@CheckReturnValue
@GwtIncompatible("java.util.regex")
public static Splitter onPattern(String separatorPattern) 

Source Link

Document

Returns a splitter that considers any subsequence matching a given pattern (regular expression) to be a separator.

Usage

From source file:org.apache.sentry.provider.db.generic.service.thrift.SentryGenericPolicyProcessor.java

public static List<NotificationHandler> createHandlers(Configuration conf) throws SentryConfigurationException {

    List<NotificationHandler> handlers = Lists.newArrayList();
    Iterable<String> notificationHandlers = Splitter.onPattern("[\\s,]").trimResults().omitEmptyStrings()
            .split(conf.get(PolicyStoreConstants.SENTRY_GENERIC_POLICY_NOTIFICATION, ""));
    try {/*from www.jav a2  s . c  o m*/
        for (String notificationHandler : notificationHandlers) {
            handlers.add(createInstance(notificationHandler, conf, NotificationHandler.class));
        }
    } catch (Exception e) {
        throw new SentryConfigurationException("Create notificationHandlers error: " + e.getMessage(), e);
    }
    return handlers;
}

From source file:bspkrs.util.config.ConfigCategory.java

public void write(BufferedWriter out, int indent) throws IOException {
    String pad0 = getIndent(indent);
    String pad1 = getIndent(indent + 1);
    String pad2 = getIndent(indent + 2);

    if (comment != null && !comment.isEmpty()) {
        write(out, pad0, COMMENT_SEPARATOR);
        write(out, pad0, "# ", name);
        write(out, pad0,/*from ww w  .  jav a  2s .co  m*/
                "#--------------------------------------------------------------------------------------------------------#");
        Splitter splitter = Splitter.onPattern("\r?\n");

        for (String line : splitter.split(comment)) {
            write(out, pad0, "# ", line);
        }

        write(out, pad0, COMMENT_SEPARATOR, NEW_LINE);
    }

    if (!allowedProperties.matchesAllOf(name)) {
        name = '"' + name + '"';
    }

    write(out, pad0, name, " {");

    Property[] props = getOrderedValuesArray();

    for (int x = 0; x < props.length; x++) {
        Property prop = props[x];

        if (prop.comment != null && !prop.comment.isEmpty()) {
            if (x != 0) {
                out.newLine();
            }

            Splitter splitter = Splitter.onPattern("\r?\n");
            for (String commentLine : splitter.split(prop.comment)) {
                write(out, pad1, "# ", commentLine);
            }
        }

        String propName = prop.getName();

        if (!allowedProperties.matchesAllOf(propName)) {
            propName = '"' + propName + '"';
        }

        if (prop.isList()) {
            char type = prop.getType().getID();

            write(out, pad1, String.valueOf(type), ":", propName, " <");

            for (String line : prop.getStringList()) {
                write(out, pad2, line);
            }

            write(out, pad1, " >");
        } else if (prop.getType() == null) {
            write(out, pad1, propName, "=", prop.getString());
        } else {
            char type = prop.getType().getID();
            write(out, pad1, String.valueOf(type), ":", propName, "=", prop.getString());
        }
    }

    if (children.size() > 0)
        out.newLine();

    for (ConfigCategory child : children) {
        child.write(out, indent + 1);
    }

    write(out, pad0, "}", NEW_LINE);
}

From source file:edu.umich.robot.SoarParametersView.java

public void showDialog(JFrame top) {
    final JDialog d = new JDialog(top, "Soar Parameters");
    cancel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            d.dispose();//from   w ww  . j  a v  a  2  s .  co  m
        }
    });

    ok.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            for (Map.Entry<LearnSetting, JRadioButton> entry : learnButtons.entrySet())
                if (entry.getValue().isSelected())
                    properties.set(AgentProperties.LEARN, entry.getKey());

            properties.set(AgentProperties.EPMEM_LEARNING, epmemLearn.isSelected());
            properties.set(AgentProperties.SMEM_LEARNING, smemLearn.isSelected());

            Splitter splitter = Splitter.onPattern("\\s+");
            List<String> exclusions = Lists.newArrayList(splitter.split(epmemExclusions.getText()));
            properties.set(AgentProperties.EPMEM_EXCLUSIONS, exclusions.toArray(new String[exclusions.size()]));

            for (Map.Entry<PropertyKey<String>, JTextField> entry : spFields.entrySet())
                properties.set(entry.getKey(), entry.getValue().getText());

            for (Map.Entry<Mission, JRadioButton> entry : missionButtons.entrySet())
                if (entry.getValue().isSelected())
                    properties.set(AgentProperties.MISSION, entry.getKey());

            splitter = Splitter.on("\n").omitEmptyStrings();
            List<String> miscCommands = Lists.newArrayList(splitter.split(misc.getText()));
            properties.set(AgentProperties.MISC_COMMANDS,
                    miscCommands.toArray(new String[miscCommands.size()]));

            d.dispose();
        }
    });

    d.setContentPane(panel);
    d.pack();
    d.setLocationRelativeTo(top);
    d.setVisible(true);
}

From source file:com.mattc.launcher.util.Console.java

/**
 * Takes a Throwable and prints out the Stack Trace. This is <br />
 * basically equivalent to Throwable.printStackTrace().
 * //from  w w w.  java 2 s .  c om
 * @param e
 */
public static void exception(Throwable e) {
    final Splitter splitter = Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings();
    final Iterator<String> trace = splitter.split(Throwables.getStackTraceAsString(e)).iterator();

    error("===============EXCEPTION===============");
    error("");
    error(String.format("MESSAGE (T:%s): %s", e.getClass().getSimpleName(), e.getLocalizedMessage()));
    error(" " + trace.next());
    Iterators.advance(trace, 1);

    while (trace.hasNext()) {
        error(" \t" + trace.next());
    }

    logger.error("");
    logger.error("===============EXCEPTION===============");
}

From source file:software.betamax.proxy.BetamaxFilters.java

private DefaultFullHttpResponse playRecordedResponse(Response recordedResponse) throws IOException {
    DefaultFullHttpResponse response;// w w w  . j av a  2  s . c  o m
    HttpResponseStatus status = HttpResponseStatus.valueOf(recordedResponse.getStatus());
    if (recordedResponse.hasBody()) {
        ByteBuf content = getEncodedContent(recordedResponse);
        response = new DefaultFullHttpResponse(HTTP_1_1, status, content);
    } else {
        response = new DefaultFullHttpResponse(HTTP_1_1, status);
    }
    for (Map.Entry<String, String> header : recordedResponse.getHeaders().entrySet()) {
        response.headers().set(header.getKey(), Splitter.onPattern(",\\s*").split(header.getValue()));
    }
    return response;
}

From source file:org.robotframework.ide.eclipse.main.plugin.tableeditor.source.SuiteSourceFormattingStrategy.java

private String formatWithDynamicSeparator(final String content, final String delimiter,
        final FormatterProperties properties) {
    String tabsFreeContent;//from  w  w  w  .  j a  v  a2 s . c  om
    try (BufferedReader reader = new BufferedReader(new StringReader(content))) {
        final StringBuilder contentWithoutTabs = new StringBuilder();
        String line = reader.readLine();
        while (line != null) {
            contentWithoutTabs.append(line.replaceAll("\t", "  "));
            contentWithoutTabs.append(delimiter);
            line = reader.readLine();
        }
        tabsFreeContent = contentWithoutTabs.toString();
    } catch (final IOException e) {
        return content;
    }

    final Map<Integer, Integer> columnsLength = Maps.newHashMap();
    try (BufferedReader reader = new BufferedReader(new StringReader(tabsFreeContent))) {
        String line = reader.readLine();
        while (line != null) {
            updateCellLengths(line, columnsLength);

            line = reader.readLine();
        }
    } catch (final IOException e) {
        return content;
    }

    try (BufferedReader reader = new BufferedReader(new StringReader(tabsFreeContent))) {
        final StringBuilder formattedContent = new StringBuilder();
        String line = reader.readLine();
        while (line != null) {
            int column = 0;
            final StringBuilder formattedLine = new StringBuilder();
            for (final String cell : Splitter.onPattern("  +").splitToList(line)) {
                formattedLine.append(Strings.padEnd(cell, columnsLength.get(column), ' '));
                formattedLine.append(Strings.repeat(" ", properties.separatorLength));
                column++;
            }
            formattedContent.append(formattedLine.toString().replaceAll(" +$", ""));
            formattedContent.append(delimiter);

            line = reader.readLine();
        }
        return formattedContent.toString();

    } catch (final IOException e) {
        return content;
    }
}

From source file:fr.obeo.intent.specification.parser.SpecificationParser.java

/**
 * Parse the stories./*from ww w  .  ja  va2  s  . c  o m*/
 * 
 * @param intentSection
 *            Intent Section
 * @param validElements
 *            Valid elements
 */
private void parseStories(final IntentSection intentSection, final StringBuffer validElements) {
    // Get valid stories
    StringBuffer validStories = new StringBuffer();
    for (String element : Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings().split(validElements)) {
        if (isStory(element)) {
            validStories.append(element + "\n");
        }
    }

    // "Story:"
    final String storyPattern = SpecificationKeyword.STORY.value + COLON;
    for (String description : Splitter.onPattern(storyPattern).trimResults().omitEmptyStrings()
            .split(validStories)) {
        Map<String, String> result = Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings()
                .withKeyValueSeparator(COLON).split(storyPattern + description);
        String storyDescription = result.get(SpecificationKeyword.STORY.value);

        final String storyName = storyDescription.substring(0, storyDescription.indexOf(OPEN_BRACKET)).trim();

        NamedElement namedElement = getNamedElement(storyName, Story.class);
        Story story = null;
        if (namedElement == null) {
            story = specificationFactory.createStory();
            story.setName(storyName);
            specification.getStories().add((Story) story);
            parsedElements.add(new ParsedElement(intentSection, story));
        } else if (namedElement instanceof Story) {
            story = (Story) namedElement;
        } else {
            throw new UnsupportedOperationException();
        }

        String features = storyDescription.substring(storyDescription.indexOf(OPEN_BRACKET) + 1,
                storyDescription.indexOf(CLOSE_BRACKET));
        for (String featureName : Splitter.on(COMMA).trimResults().omitEmptyStrings().split(features)) {
            namedElement = getNamedElement(featureName, Feature.class);
            Feature feature = null;
            if (namedElement == null) {
                feature = specificationFactory.createFeature();
                feature.setName(featureName);
                specification.getFeatures().add(feature);
                parsedElements.add(new ParsedElement(intentSection, feature));
            } else if (namedElement instanceof Feature) {
                feature = (Feature) namedElement;
            } else {
                throw new UnsupportedOperationException();
            }
            feature.getStories().add((Story) story);
        }

        if (result.containsKey(SpecificationKeyword.AS.value)) {
            String roleName = result.get(SpecificationKeyword.AS.value).trim();
            namedElement = getNamedElement(roleName, Role.class);
            Role role = null;
            if (namedElement == null) {
                role = specificationFactory.createRole();
                role.setName(roleName);
                specification.getRoles().add(role);
            } else if (namedElement instanceof Role) {
                role = (Role) namedElement;
            } else {
                throw new UnsupportedOperationException();
            }
            story.setAs(role);

            String capabilityName = result.get(SpecificationKeyword.I_WANT.value).trim();
            namedElement = getNamedElement(capabilityName, Capability.class);
            Capability capability = null;
            if (namedElement == null) {
                capability = specificationFactory.createCapability();
                capability.setName(capabilityName);
                specification.getCapabilities().add(capability);
            } else if (namedElement instanceof Capability) {
                capability = (Capability) namedElement;
            } else {
                throw new UnsupportedOperationException();
            }
            story.setIWant(capability);

            String benefitName = result.get(SpecificationKeyword.SO_THAT.value).trim();
            namedElement = getNamedElement(benefitName, Benefit.class);
            Benefit benefit = null;
            if (namedElement == null) {
                benefit = specificationFactory.createBenefit();
                benefit.setName(benefitName);
                specification.getBenefits().add(benefit);
            } else if (namedElement instanceof Benefit) {
                benefit = (Benefit) namedElement;
            } else {
                throw new UnsupportedOperationException();
            }
            story.setSoThat(benefit);
        }
    }
}

From source file:com.commercehub.bamboo.plugins.grailswrapper.GrailsWrapperTask.java

@NotNull
private Iterable<List<String>> parseCommands(@NotNull TaskContext taskContext) {
    ConfigurationMap configurationMap = taskContext.getConfigurationMap();
    String rawCommands = configurationMap.get(GrailsWrapperTaskConfigurator.COMMANDS);
    String rawCommonOpts = configurationMap.get(GrailsWrapperTaskConfigurator.COMMON_OPTIONS);
    String commonOpts = Utils.ensureEndsWith(Strings.nullToEmpty(rawCommonOpts), " ");
    Splitter splitter = Splitter.onPattern("[\r\n]").trimResults().omitEmptyStrings();
    Iterable<String> splitCommands = splitter.split(rawCommands);
    Function<String, String> commonOptsFunction = new StringPrependFunction(commonOpts);
    Function<String, List<String>> tokenizeFunction = CommandlineStringUtils.tokeniseCommandlineFunction();
    return Iterables.transform(splitCommands, Functions.compose(tokenizeFunction, commonOptsFunction));
}

From source file:org.apache.sentry.provider.db.service.thrift.SentryPolicyStoreProcessor.java

@VisibleForTesting
static List<NotificationHandler> createHandlers(Configuration conf) throws SentryConfigurationException {
    List<NotificationHandler> handlers = Lists.newArrayList();
    Iterable<String> notificationHandlers = Splitter.onPattern("[\\s,]").trimResults().omitEmptyStrings()
            .split(conf.get(PolicyStoreServerConfig.NOTIFICATION_HANDLERS, ""));
    for (String notificationHandler : notificationHandlers) {
        Class<?> clazz = null;
        try {//from   w ww.j a va  2s.c o m
            clazz = Class.forName(notificationHandler);
            if (!NotificationHandler.class.isAssignableFrom(clazz)) {
                throw new SentryConfigurationException(
                        "Class " + notificationHandler + " is not a " + NotificationHandler.class.getName());
            }
        } catch (ClassNotFoundException e) {
            throw new SentryConfigurationException("Value " + notificationHandler + " is not a class", e);
        }
        Preconditions.checkNotNull(clazz, "Error class cannot be null");
        try {
            Constructor<?> constructor = clazz.getConstructor(Configuration.class);
            handlers.add((NotificationHandler) constructor.newInstance(conf));
        } catch (Exception e) {
            throw new SentryConfigurationException("Error attempting to create " + notificationHandler, e);
        }
    }
    return handlers;
}

From source file:net.minecraftforge.common.config.ConfigCategory.java

public void write(BufferedWriter out, int indent) throws IOException {
    String pad0 = getIndent(indent);
    String pad1 = getIndent(indent + 1);
    String pad2 = getIndent(indent + 2);

    if (comment != null && !comment.isEmpty()) {
        write(out, pad0, COMMENT_SEPARATOR);
        write(out, pad0, "# ", name);
        write(out, pad0,/*from  w  w w.j av  a 2s . c o m*/
                "#--------------------------------------------------------------------------------------------------------#");
        Splitter splitter = Splitter.onPattern("\r?\n");

        for (String line : splitter.split(comment)) {
            write(out, pad0, "# ", line);
        }

        write(out, pad0, COMMENT_SEPARATOR, NEW_LINE);
    }

    String displayName = name;

    if (!allowedProperties.matchesAllOf(name)) {
        displayName = '"' + name + '"';
    }

    write(out, pad0, displayName, " {");

    Property[] props = getOrderedValues().toArray(new Property[] {});

    for (int x = 0; x < props.length; x++) {
        Property prop = props[x];

        if (prop.comment != null && !prop.comment.isEmpty()) {
            if (x != 0) {
                out.newLine();
            }

            Splitter splitter = Splitter.onPattern("\r?\n");
            for (String commentLine : splitter.split(prop.comment)) {
                write(out, pad1, "# ", commentLine);
            }
        }

        String propName = prop.getName();

        if (!allowedProperties.matchesAllOf(propName)) {
            propName = '"' + propName + '"';
        }

        if (prop.isList()) {
            char type = prop.getType().getID();

            write(out, pad1, String.valueOf(type), ":", propName, " <");

            for (String line : prop.getStringList()) {
                write(out, pad2, line);
            }

            write(out, pad1, " >");
        } else if (prop.getType() == null) {
            write(out, pad1, propName, "=", prop.getString());
        } else {
            char type = prop.getType().getID();
            write(out, pad1, String.valueOf(type), ":", propName, "=", prop.getString());
        }
    }

    if (children.size() > 0)
        out.newLine();

    for (ConfigCategory child : children) {
        child.write(out, indent + 1);
    }

    write(out, pad0, "}", NEW_LINE);
}