Пример #1
0
 /**
  * Gets the svn revision, from the svn log revision output.
  *
  * @param revisionOutput
  * @return the svn revision
  */
 private String getRevision(final String revisionOutput) {
   if (REVISION_REG_EXP1.match(revisionOutput)) {
     return REVISION_REG_EXP1.getParen(1);
   } else if (REVISION_REG_EXP2.match(revisionOutput)) {
     return REVISION_REG_EXP2.getParen(1);
   } else {
     throw new IllegalOutputException(revisionOutput);
   }
 }
  /**
   * Add a webLinkedFile in the queue if it hasn't been already downloaded and if it respect the
   * good host or protocol
   *
   * @param uri the URI to add
   * @param depth the depth of the URI
   * @param parent the webHtmlFile parent
   */
  public void addLinkedFile(URI uri, int depth, WebFile parent) {
    // creates the webLinkedFile according to the URI
    if (!isUriAlreadyDownloaded(uri)) {
      // verification if the depth is good
      if (depth <= maxDepth) {
        discoveredURI.add(Utils.getCompletePath(uri));
        WebLinkedFile webLinkedFile = new WebLinkedFile(uri, depth, parent);
        String webFileHost = Utils.getCompleteHost(webLinkedFile.getURI());

        // filter the linked files with the Filter
        RE r = new RE(regExp);
        if (r.match(webLinkedFile.getFileName())) {
          if (webFileHost.equals(defaultHost)) {
            linkedFileToDownload.add(webLinkedFile);
            // add the webHtmlFile in the treeModel
            DiscoveryTreeNode parentNode = (DiscoveryTreeNode) treeRoot.getChild(parent);
            DiscoveryTreeNode node = parentNode.add(webLinkedFile);
            treeModel.nodesWereInserted(parentNode, new int[] {parentNode.getIndex(node)});
            // add the webHtmlFile in the detailledModel
            detailledModel.addElement(webLinkedFile);
          } else {
            // it is not the same web site or the same protocol
            System.err.println(
                webLinkedFile.getURI()
                    + " / "
                    + defaultHost
                    + ": NOT THE SAME HOST OR THE SAME PROTOCOL");
          }
        }
      }
    }
  }
  /** {@inheritDoc} */
  public void consumeLine(String line) {
    if (lineRegexp.match(line)) {
      String revision = lineRegexp.getParen(1).trim();

      lines.add(new BlameLine(null, revision, null));
    }
  }
Пример #4
0
  /**
   * Process the current input line in the GET_FILE state. This state adds each file entry line to
   * the current change log entry. Note, the revision number for the entire entry is used for the
   * revision number of each file.
   *
   * @param line A line of text from the svn log output
   */
  private void processGetFile(String line) {
    if (FILE_PATTERN.match(line)) {
      final String fileinfo = FILE_PATTERN.getParen(2);
      String name = fileinfo;
      String originalName = null;
      String originalRev = null;
      final int n = fileinfo.indexOf(" (");
      if (n > 1 && fileinfo.endsWith(")")) {
        final String origFileInfo = fileinfo.substring(n);
        if (ORIG_FILE_PATTERN.match(origFileInfo)) {
          // if original file is present, we must extract the affected one from the beginning
          name = fileinfo.substring(0, n);
          originalName = ORIG_FILE_PATTERN.getParen(1);
          originalRev = ORIG_FILE_PATTERN.getParen(2);
        }
      }
      final String actionStr = FILE_PATTERN.getParen(1);
      final ScmFileStatus action;
      if ("A".equals(actionStr)) {
        // TODO: this may even change to MOVED if we later explore whole changeset and find matching
        // DELETED
        action = originalRev == null ? ScmFileStatus.ADDED : ScmFileStatus.COPIED;
      } else if ("D".equals(actionStr)) {
        action = ScmFileStatus.DELETED;
      } else if ("M".equals(actionStr)) {
        action = ScmFileStatus.MODIFIED;
      } else if ("R".equals(actionStr)) {
        action = ScmFileStatus.UPDATED; // == REPLACED in svn terms
      } else {
        action = ScmFileStatus.UNKNOWN;
      }
      System.out.println(actionStr + " : " + name);
      final ChangeFile changeFile = new ChangeFile(name, currentRevision);
      changeFile.setAction(action);
      changeFile.setOriginalName(originalName);
      changeFile.setOriginalRevision(originalRev);
      currentChange.addFile(changeFile);

      status = GET_FILE;
    } else if (line.equals(FILE_END_TOKEN)) {
      // Create a buffer for the collection of the comment now
      // that we are leaving the GET_FILE state.
      currentComment = new StringBuilder();

      status = GET_COMMENT;
    }
  }
Пример #5
0
  /**
   * A parameter expansion algorithm, designed to replace strings delimited by percent signs '%'
   * with a value supplied by a Map object.
   *
   * <p>NOTE: This function only replaces one particular parameter, the <code>%noticeid%</code>
   * parameter.
   *
   * @param input the input string
   * @param paramMap a map that will supply the substitution values
   * @return a {@link java.lang.String} object.
   */
  public static String expandNotifParms(final String input, final Map<String, String> paramMap) {
    String expanded = input;

    if (m_expandRE.match(expanded)) {
      String key = m_expandRE.getParen(1);
      Assert.isTrue("noticeid".equals(key));
      String replace = paramMap.get(key);
      if (replace != null) {
        expanded = m_expandRE.subst(expanded, replace);
      }
    }
    return expanded;
  }
Пример #6
0
 public static boolean validaCorreoElectronico(String correo) {
   boolean flag = false;
   if (correo != null && correo.trim().length() != 0) {
     try {
       RE re =
           new RE(
               "^[a-zA-Z](-|[a-zA-Z0-9\\._])*[a-zA-Z0-9]@[a-zA-Z0-9](-|[a-zA-Z0-9\\._])*[a-zA-Z0-9][\\.][a-zA-Z](-|[a-zA-Z0-9\\._])*[a-zA-Z]$");
       flag = re.match(correo.trim());
     } catch (RESyntaxException e) {
       e.printStackTrace();
     }
   }
   return flag;
 }
Пример #7
0
  /**
   * Converts the date time stamp from the svn output into a date object.
   *
   * @param dateOutput The date output from an svn log command.
   * @return A date representing the time stamp of the log entry.
   */
  private Date getDate(final String dateOutput) {
    if (!DATE_REG_EXP.match(dateOutput)) {
      throw new IllegalOutputException(dateOutput);
    }

    final StringBuilder date = new StringBuilder();
    date.append(DATE_REG_EXP.getParen(1));
    date.append(" GMT");
    date.append(DATE_REG_EXP.getParen(2));
    date.append(DATE_REG_EXP.getParen(3));
    date.append(':');
    date.append(DATE_REG_EXP.getParen(4));

    return parseDate(date.toString(), userDateFormat, SVN_TIMESTAMP_PATTERN);
  }
  public void consumeLine(String line) {
    if (lineRegexp.match(line)) {
      String revision = lineRegexp.getParen(1);
      // SCM-613
      String author = lineRegexp.getParen(2).toLowerCase();
      String dateTimeStr = lineRegexp.getParen(3);

      Date dateTime = parseDate(dateTimeStr, null, CLEARCASE_TIMESTAMP_PATTERN);
      lines.add(new BlameLine(dateTime, revision, author));

      if (getLogger().isDebugEnabled()) {
        getLogger().debug(author + " " + dateTimeStr);
      }
    }
  }
Пример #9
0
  /**
   * Process the current input line in the GET_HEADER state. The author, date, and the revision of
   * the entry are gathered. Note, Subversion does not have per-file revisions, instead, the entire
   * repository is given a single revision number, which is used for the revision number of each
   * file.
   *
   * @param line A line of text from the svn log output
   */
  private void processGetHeader(String line) {
    if (!HEADER_REG_EXP.match(line)) {
      // The header line is not found. Intentionally do nothing.
      return;
    }

    currentRevision = getRevision(HEADER_REG_EXP.getParen(REVISION_GROUP));

    currentChange = new SvnChangeSet();

    currentChange.setAuthor(HEADER_REG_EXP.getParen(AUTHOR_GROUP));

    currentChange.setDate(getDate(HEADER_REG_EXP.getParen(DATE_GROUP)));

    currentChange.setRevision(currentRevision);

    status = GET_FILE;
  }
Пример #10
0
  /**
   * Test to see if the passed host-port pair is the endpoint for an SMTP server. If there is an
   * SMTP server at that destination then a value of true is returned from the method. Otherwise a
   * false value is returned to the caller.
   *
   * @param host The remote host to connect to.
   * @param port The remote port on the host.
   * @return True if server supports SMTP on the specified port, false otherwise
   */
  private boolean isServer(InetAddress host, int port, int retries, int timeout) {
    // get a log to send errors
    //
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    boolean isAServer = false;
    for (int attempts = 0; attempts <= retries && !isAServer; attempts++) {
      Socket socket = null;
      try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(host, port), timeout);
        socket.setSoTimeout(timeout);
        log.debug("SmtpPlugin: connected to host: " + host + " on port: " + port);

        // Allocate a line reader
        //
        BufferedReader lineRdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        // Read responses from the server. The initial line should just
        // be a banner, but go ahead and check for multiline response.
        //
        String result = null;
        do {
          result = lineRdr.readLine();

        } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result));

        if (result == null || result.length() == 0) {
          log.info("Received truncated response from SMTP server " + InetAddressUtils.str(host));
          continue;
        }

        // Tokenize the last line result
        //
        StringTokenizer t = new StringTokenizer(result);
        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());

          // Response from HELO command may be a multi-line response
          // (but
          // most likely will be single-line)..
          // We are expecting to get a response with an integer return
          // code in the first token. We can't ge sure that the first
          // response will give us what we want. Consider the
          // following
          // reponse for example:
          //
          // 250-First line
          // 250-Second line
          // 250 Requested mail action okay, completed
          //
          // In this case the final line of the response contains the
          // return
          // code we are looking for.
          do {
            result = lineRdr.readLine();

          } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result));

          if (result == null || result.length() == 0) {
            log.info("Received truncated response from SMTP server " + InetAddressUtils.str(host));
            continue;
          }

          t = new StringTokenizer(result);
          rc = Integer.parseInt(t.nextToken());
          if (rc == 250) {
            //
            // Send the QUIT command
            //
            cmd = "QUIT\r\n";
            socket.getOutputStream().write(cmd.getBytes());

            // Response from QUIT command may be a multi-line
            // response.
            // We are expecting to get a response with an integer
            // return
            // code in the first token. We can't ge sure that the
            // first
            // response will give us what we want. Consider the
            // following
            // reponse for example:
            //
            // 221-First line
            // 221-Second line
            // 221 <domain> Service closing transmission channel.
            //
            // In this case the final line of the response contains
            // the return
            // code we are looking for.
            do {
              result = lineRdr.readLine();

            } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result));

            if (result == null || result.length() == 0) {
              log.info(
                  "Received truncated response from SMTP server " + InetAddressUtils.str(host));
              continue;
            }

            t = new StringTokenizer(result);
            rc = Integer.parseInt(t.nextToken());

            if (rc == 221) isAServer = true;
          }
        }
      } catch (NumberFormatException e) {
        log.info(
            "SmtpPlugin: received invalid result code from server " + InetAddressUtils.str(host),
            e);
        isAServer = false;
      } catch (ConnectException cE) {
        // Connection refused!! Continue to retry.
        //
        log.debug("SmtpPlugin: connection refused to " + InetAddressUtils.str(host) + ":" + port);
        isAServer = false;
      } catch (NoRouteToHostException e) {
        // No route to host!! No need to perform retries.
        e.fillInStackTrace();
        log.info(
            "SmtpPlugin: Unable to test host "
                + InetAddressUtils.str(host)
                + ", no route available",
            e);
        isAServer = false;
        throw new UndeclaredThrowableException(e);
      } catch (InterruptedIOException e) {
        log.debug(
            "SmtpPlugin: did not connect to host within timeout: "
                + timeout
                + " attempt: "
                + attempts);
        isAServer = false;
      } catch (IOException e) {
        log.info("SmtpPlugin: Error communicating with host " + InetAddressUtils.str(host), e);
        isAServer = false;
      } catch (Throwable t) {
        log.warn(
            "SmtpPlugin: Undeclared throwable exception caught contacting host "
                + InetAddressUtils.str(host),
            t);
        isAServer = false;
      } finally {
        try {
          if (socket != null) socket.close();
        } catch (IOException e) {
        }
      }
    }

    //
    // return the success/failure of this
    // attempt to contact an SMTP server.
    //
    return isAServer;
  }
Пример #11
0
  /**
   * {@inheritDoc}
   *
   * <p>Poll an {@link InetAddress} for SSH availability.
   *
   * <p>During the poll an attempt is made to connect on the specified port. If the connection
   * request is successful, the banner line generated by the interface is parsed and if the banner
   * text indicates that we are talking to Provided that the interface's response is valid we mark
   * the poll status as available and return.
   */
  public PollStatus poll(InetAddress address, Map<String, Object> parameters) {

    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);

    int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
    String banner = ParameterMap.getKeyedString(parameters, "banner", null);
    String match = ParameterMap.getKeyedString(parameters, "match", null);
    String clientBanner =
        ParameterMap.getKeyedString(parameters, "client-banner", Ssh.DEFAULT_CLIENT_BANNER);
    PollStatus ps = PollStatus.unavailable();

    Ssh ssh = new Ssh(address, port, tracker.getConnectionTimeout());
    ssh.setClientBanner(clientBanner);

    RE regex = null;
    try {
      if (match == null && (banner == null || banner.equals("*"))) {
        regex = null;
      } else if (match != null) {
        regex = new RE(match);
      } else if (banner != null) {
        regex = new RE(banner);
      }
    } catch (final RESyntaxException e) {
      final String matchString = match == null ? banner : match;
      LogUtils.infof(
          this,
          "Invalid regular expression for SSH banner match /%s/: %s",
          matchString,
          e.getMessage());
      LogUtils.debugf(this, e, "Invalid Regular expression for SSH banner match /%s/", matchString);
    }

    for (tracker.reset(); tracker.shouldRetry() && !ps.isAvailable(); tracker.nextAttempt()) {
      try {
        ps = ssh.poll(tracker);
      } catch (final InsufficientParametersException e) {
        LogUtils.errorf(this, e, "An error occurred polling host '%s'", address);
        break;
      }

      if (!ps.isAvailable()) {
        // not able to connect, retry
        continue;
      }

      // If banner matching string is null or wildcard ("*") then we
      // only need to test connectivity and we've got that!

      if (regex == null) {
        return ps;
      } else {
        String response = ssh.getServerBanner();

        if (response == null) {
          return PollStatus.unavailable("server closed connection before banner was received.");
        }

        if (regex.match(response)) {
          LogUtils.debugf(this, "isServer: matching response=%s", response);
          return ps;
        } else {
          // Got a response but it didn't match... no need to attempt
          // retries
          LogUtils.debugf(this, "isServer: NON-matching response=%s", response);
          return PollStatus.unavailable(
              "server responded, but banner did not match '" + banner + "'");
        }
      }
    }
    return ps;
  }
Пример #12
0
  /**
   * Test to see if the passed host-port pair is the endpoint for a TCP server. If there is a TCP
   * server at that destination then a value of true is returned from the method. Otherwise a false
   * value is returned to the caller. In order to return true the remote host must generate a banner
   * line which contains the text from the bannerMatch argument.
   *
   * @param host The remote host to connect to.
   * @param port The remote port on the host.
   * @param bannerResult Banner line generated by the remote host must contain this text.
   * @return True if a connection is established with the host and the banner line contains the
   *     bannerMatch text.
   */
  private boolean isServer(
      InetAddress host, int port, int retries, int timeout, RE regex, StringBuffer bannerResult) {
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    boolean isAServer = false;
    for (int attempts = 0; attempts <= retries && !isAServer; attempts++) {
      Socket socket = null;
      try {
        // create a connected socket
        //
        socket = new Socket();
        socket.connect(new InetSocketAddress(host, port), timeout);
        socket.setSoTimeout(timeout);
        log.debug("TcpPlugin: connected to host: " + host + " on port: " + port);

        // If banner matching string is null or wildcard ("*") then we
        // only need to test connectivity and we've got that!
        //
        if (regex == null) {
          isAServer = true;
        } else {
          // get a line reader
          //
          BufferedReader lineRdr =
              new BufferedReader(new InputStreamReader(socket.getInputStream()));

          // Read the server's banner line ouptput and validate it
          // against
          // the bannerMatch parameter to determine if this interface
          // supports the
          // service.
          //
          String response = lineRdr.readLine();
          if (regex.match(response)) {
            if (log.isDebugEnabled()) log.debug("isServer: matching response=" + response);
            isAServer = true;
            if (bannerResult != null) bannerResult.append(response);
          } else {
            // Got a response but it didn't match...no need to
            // attempt retries
            isAServer = false;
            if (log.isDebugEnabled()) log.debug("isServer: NON-matching response=" + response);
            break;
          }
        }
      } catch (ConnectException e) {
        // Connection refused!! Continue to retry.
        //
        log.debug("TcpPlugin: Connection refused to " + InetAddressUtils.str(host) + ":" + port);
        isAServer = false;
      } catch (NoRouteToHostException e) {
        // No Route to host!!!
        //
        e.fillInStackTrace();
        log.info(
            "TcpPlugin: Could not connect to host "
                + InetAddressUtils.str(host)
                + ", no route to host",
            e);
        isAServer = false;
        throw new UndeclaredThrowableException(e);
      } catch (InterruptedIOException e) {
        // This is an expected exception
        //
        log.debug(
            "TcpPlugin: did not connect to host within timeout: "
                + timeout
                + " attempt: "
                + attempts);
        isAServer = false;
      } catch (IOException e) {
        log.info(
            "TcpPlugin: An expected I/O exception occured connecting to host "
                + InetAddressUtils.str(host)
                + " on port "
                + port,
            e);
        isAServer = false;
      } catch (Throwable t) {
        isAServer = false;
        log.warn(
            "TcpPlugin: An undeclared throwable exception was caught connecting to host "
                + InetAddressUtils.str(host)
                + " on port "
                + port,
            t);
      } finally {
        try {
          if (socket != null) socket.close();
        } catch (IOException e) {
        }
      }
    }

    //
    // return the success/failure of this
    // attempt to contact an ftp server.
    //
    return isAServer;
  }