Search in sources :

Example 36 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project kotlin by JetBrains.

the class DefaultConfiguration method addRegexp.

private void addRegexp(@NonNull String idList, @NonNull Iterable<String> ids, int n, @NonNull String regexp, boolean silent) {
    try {
        if (mRegexps == null) {
            mRegexps = new HashMap<String, List<Pattern>>();
        }
        Pattern pattern = Pattern.compile(regexp);
        for (String id : ids) {
            List<Pattern> paths = mRegexps.get(id);
            if (paths == null) {
                paths = new ArrayList<Pattern>(n / 2 + 1);
                mRegexps.put(id, paths);
            }
            paths.add(pattern);
        }
    } catch (PatternSyntaxException e) {
        if (!silent) {
            formatError("Invalid pattern %1$s under %2$s: %3$s", regexp, idList, e.getDescription());
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 37 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project opennms by OpenNMS.

the class SmtpMonitor method poll.

/**
 * {@inheritDoc}
 *
 * <P>
 * Poll the specified address for SMTP service availability.
 * </P>
 *
 * <P>
 * During the poll an attempt is made to connect on the specified port (by
 * default TCP port 25). If the connection request is successful, the banner
 * line generated by the interface is parsed and if the extracted return
 * code indicates that we are talking to an SMTP server we continue. Next,
 * an SMTP 'HELO' command is sent to the interface. Again the response is
 * parsed and a return code extracted and verified. Finally, an SMTP 'QUIT'
 * command is sent. Provided that the interface's response is valid we set
 * the service status to SERVICE_AVAILABLE and return.
 * </P>
 */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
    InetAddress ipAddr = svc.getAddress();
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);
    PollStatus serviceStatus = PollStatus.unavailable();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        Socket socket = null;
        try {
            // create a connected socket
            // 
            tracker.startAttempt();
            socket = new Socket();
            socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
            socket.setSoTimeout(tracker.getSoTimeout());
            LOG.debug("SmtpMonitor: connected to host: {} on port: {}", ipAddr, port);
            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.unresponsive();
            // Forcing to check for CRLF instead of any other line terminator as per RFC specification
            CRLFLineReader rdr = new CRLFLineReader(new InputStreamReader(socket.getInputStream(), "ASCII"));
            // 
            // Tokenize the Banner Line, and check the first
            // line for a valid return.
            // 
            String banner = sendMessage(socket, rdr, null);
            LOG.debug("poll: banner = {}", banner);
            StringTokenizer t = new StringTokenizer(banner);
            int rc = Integer.parseInt(t.nextToken());
            if (rc == 220) {
                // 
                // Send the HELO command
                // 
                String cmd = "HELO " + LOCALHOST_NAME + "\r\n";
                socket.getOutputStream().write(cmd.getBytes());
                // 
                // get the returned string, tokenize, and
                // verify the correct output.
                // 
                String response = rdr.readLine();
                double responseTime = tracker.elapsedTimeInMillis();
                if (response == null) {
                    continue;
                }
                if (MULTILINE.matcher(response).find()) {
                    // Ok we have a multi-line response...first three
                    // chars of the response line are the return code.
                    // The last line of the response will start with
                    // return code followed by a space.
                    String multiLineRC = new String(response.getBytes("ASCII"), 0, 3, "ASCII");
                    // Create new regExp to look for last line
                    // of this multi line response
                    Pattern endMultiline = null;
                    try {
                        endMultiline = Pattern.compile(multiLineRC);
                    } catch (PatternSyntaxException ex) {
                        throw new java.lang.reflect.UndeclaredThrowableException(ex);
                    }
                    // response
                    do {
                        response = rdr.readLine();
                    } while (response != null && !endMultiline.matcher(response).find());
                    if (response == null) {
                        continue;
                    }
                }
                t = new StringTokenizer(response);
                rc = Integer.parseInt(t.nextToken());
                if (rc == 250) {
                    response = sendMessage(socket, rdr, "QUIT\r\n");
                    t = new StringTokenizer(response);
                    rc = Integer.parseInt(t.nextToken());
                    if (rc == 221) {
                        serviceStatus = PollStatus.available(responseTime);
                    }
                }
            } else if (rc == 554) {
                String response = sendMessage(socket, rdr, "QUIT\r\n");
                serviceStatus = PollStatus.unavailable("Server rejecting transactions with 554");
            }
            // checking or HELO/QUIT comand process.
            if (!serviceStatus.isAvailable()) {
                serviceStatus = PollStatus.unavailable(serviceStatus.getReason());
            }
        } catch (NumberFormatException e) {
            String reason = "NumberFormatException while polling address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (NoRouteToHostException e) {
            String reason = "No route to host exception for address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            // Break out of for(;;)
            break;
        } catch (InterruptedIOException e) {
            String reason = "Did not receive expected response within timeout " + tracker;
            LOG.debug(reason);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (ConnectException e) {
            String reason = "Unable to connect to address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (IOException e) {
            String reason = "IOException while polling address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } finally {
            try {
                // Close the socket
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.fillInStackTrace();
                LOG.debug("poll: Error closing socket.", e);
            }
        }
    }
    // 
    return serviceStatus;
}
Also used : Pattern(java.util.regex.Pattern) InterruptedIOException(java.io.InterruptedIOException) PollStatus(org.opennms.netmgt.poller.PollStatus) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) CRLFLineReader(org.apache.commons.net.io.CRLFLineReader) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) NoRouteToHostException(java.net.NoRouteToHostException) StringTokenizer(java.util.StringTokenizer) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) InetAddress(java.net.InetAddress) Socket(java.net.Socket) PatternSyntaxException(java.util.regex.PatternSyntaxException) ConnectException(java.net.ConnectException)

Example 38 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project opennms by OpenNMS.

the class SmtpMonitor method sendMessage.

private String sendMessage(Socket socket, BufferedReader rdr, String command) throws IOException {
    if (command != null && !"".equals(command)) {
        socket.getOutputStream().write(command.getBytes("ASCII"));
    }
    // 
    // get the returned string, tokenize, and
    // verify the correct output.
    // 
    String response = rdr.readLine();
    if (response == null) {
        return "";
    }
    if (MULTILINE.matcher(response).find()) {
        // Ok we have a multi-line response...first three
        // chars of the response line are the return code.
        // The last line of the response will start with
        // return code followed by a space.
        String multiLineRC = new String(response.getBytes("ASCII"), 0, 3, "ASCII") + " ";
        // Create new regExp to look for last line
        // of this multi line response
        Pattern endMultiline = null;
        try {
            endMultiline = Pattern.compile(multiLineRC);
        } catch (PatternSyntaxException ex) {
            throw new java.lang.reflect.UndeclaredThrowableException(ex);
        }
        // response
        do {
            response = rdr.readLine();
        } while (response != null && !endMultiline.matcher(response).find());
        if (response == null) {
            return "";
        }
    }
    return response;
}
Also used : Pattern(java.util.regex.Pattern) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 39 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project opennms by OpenNMS.

the class ThresholdingSet method passedThresholdFilters.

/**
 * <p>passedThresholdFilters</p>
 *
 * @param resource a {@link org.opennms.netmgt.threshd.CollectionResourceWrapper} object.
 * @param thresholdEntity a {@link org.opennms.netmgt.threshd.ThresholdEntity} object.
 * @return a boolean.
 */
protected boolean passedThresholdFilters(CollectionResourceWrapper resource, ThresholdEntity thresholdEntity) {
    // Find the filters for threshold definition for selected group/dataSource
    final List<ResourceFilter> filters = thresholdEntity.getThresholdConfig().getBasethresholddef().getResourceFilters();
    if (filters.size() == 0)
        return true;
    // Threshold definition with filters must match ThresholdEntity (checking DataSource and ResourceType)
    LOG.debug("passedThresholdFilters: applying {} filters to resource {}", filters.size(), resource);
    int count = 1;
    final FilterOperator operator = thresholdEntity.getThresholdConfig().getBasethresholddef().getFilterOperator();
    boolean andResult = true;
    for (ResourceFilter f : filters) {
        LOG.debug("passedThresholdFilters: filter #{}: field={}, regex='{}'", count, f.getField(), f.getContent().orElse(null));
        count++;
        // Read Resource Attribute and apply filter rules if attribute is not null
        String attr = resource.getFieldValue(f.getField());
        if (attr != null) {
            try {
                final Pattern p = Pattern.compile(f.getContent().orElse(""));
                final Matcher m = p.matcher(attr);
                boolean pass = m.matches();
                LOG.debug("passedThresholdFilters: the value of {} is {}. Pass filter? {}", f.getField(), attr, pass);
                if (operator.equals(FilterOperator.OR) && pass) {
                    return true;
                }
                if (operator.equals(FilterOperator.AND)) {
                    andResult = andResult && pass;
                    if (andResult == false)
                        return false;
                }
            } catch (PatternSyntaxException e) {
                LOG.warn("passedThresholdFilters: the regular expression {} is invalid: {}", f.getContent().orElse(null), e.getMessage(), e);
                return false;
            }
        } else {
            LOG.warn("passedThresholdFilters: can't find value of {} for resource {}", f.getField(), resource);
            if (operator.equals(FilterOperator.AND)) {
                return false;
            }
        }
    }
    if (operator.equals(FilterOperator.AND) && andResult) {
        return true;
    }
    return false;
}
Also used : FilterOperator(org.opennms.netmgt.config.threshd.FilterOperator) Pattern(java.util.regex.Pattern) ResourceFilter(org.opennms.netmgt.config.threshd.ResourceFilter) Matcher(java.util.regex.Matcher) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 40 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project geode by apache.

the class HScanExecutor method executeCommand.

@Override
public void executeCommand(Command command, ExecutionHandlerContext context) {
    List<byte[]> commandElems = command.getProcessedCommand();
    if (commandElems.size() < 3) {
        command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ArityDef.HSCAN));
        return;
    }
    ByteArrayWrapper key = command.getKey();
    @SuppressWarnings("unchecked") Region<ByteArrayWrapper, ByteArrayWrapper> keyRegion = (Region<ByteArrayWrapper, ByteArrayWrapper>) context.getRegionProvider().getRegion(key);
    checkDataType(key, RedisDataType.REDIS_HASH, context);
    if (keyRegion == null) {
        command.setResponse(Coder.getScanResponse(context.getByteBufAllocator(), new ArrayList<String>()));
        return;
    }
    byte[] cAr = commandElems.get(2);
    String cursorString = Coder.bytesToString(cAr);
    int cursor = 0;
    Pattern matchPattern = null;
    String globMatchPattern = null;
    int count = DEFUALT_COUNT;
    try {
        cursor = Integer.parseInt(cursorString);
    } catch (NumberFormatException e) {
        command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ERROR_CURSOR));
        return;
    }
    if (cursor < 0) {
        command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ERROR_CURSOR));
        return;
    }
    if (commandElems.size() > 4) {
        try {
            byte[] bytes = commandElems.get(3);
            String tmp = Coder.bytesToString(bytes);
            if (tmp.equalsIgnoreCase("MATCH")) {
                bytes = commandElems.get(4);
                globMatchPattern = Coder.bytesToString(bytes);
            } else if (tmp.equalsIgnoreCase("COUNT")) {
                bytes = commandElems.get(4);
                count = Coder.bytesToInt(bytes);
            }
        } catch (NumberFormatException e) {
            command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ERROR_COUNT));
            return;
        }
    }
    if (commandElems.size() > 6) {
        try {
            byte[] bytes = commandElems.get(5);
            String tmp = Coder.bytesToString(bytes);
            if (tmp.equalsIgnoreCase("MATCH")) {
                bytes = commandElems.get(6);
                globMatchPattern = Coder.bytesToString(bytes);
            } else if (tmp.equalsIgnoreCase("COUNT")) {
                bytes = commandElems.get(6);
                count = Coder.bytesToInt(bytes);
            }
        } catch (NumberFormatException e) {
            command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ERROR_COUNT));
            return;
        }
    }
    if (count < 0) {
        command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ERROR_COUNT));
        return;
    }
    try {
        matchPattern = convertGlobToRegex(globMatchPattern);
    } catch (PatternSyntaxException e) {
        command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), RedisConstants.ERROR_ILLEGAL_GLOB));
        return;
    }
    List<Object> returnList = getIteration(new HashSet(keyRegion.entrySet()), matchPattern, count, cursor);
    command.setResponse(Coder.getScanResponse(context.getByteBufAllocator(), returnList));
}
Also used : Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) ByteArrayWrapper(org.apache.geode.redis.internal.ByteArrayWrapper) Region(org.apache.geode.cache.Region) PatternSyntaxException(java.util.regex.PatternSyntaxException) HashSet(java.util.HashSet)

Aggregations

PatternSyntaxException (java.util.regex.PatternSyntaxException)355 Pattern (java.util.regex.Pattern)190 Matcher (java.util.regex.Matcher)115 ArrayList (java.util.ArrayList)46 IOException (java.io.IOException)25 List (java.util.List)19 File (java.io.File)14 Map (java.util.Map)12 HashMap (java.util.HashMap)9 URL (java.net.URL)7 HashSet (java.util.HashSet)7 Iterator (java.util.Iterator)7 InvalidSettingsException (org.knime.core.node.InvalidSettingsException)7 BufferedReader (java.io.BufferedReader)6 Collection (java.util.Collection)6 LinkedList (java.util.LinkedList)5 Test (org.junit.Test)5 InputStreamReader (java.io.InputStreamReader)4 SQLException (java.sql.SQLException)4 LinkedHashMap (java.util.LinkedHashMap)4