Esempio n. 1
0
    public void run() {
      URLConnection con = null;
      try {
        con = url.openConnection();

        if ("HTTPS".equalsIgnoreCase(url.getProtocol())) {
          HttpsURLConnection scon = (HttpsURLConnection) con;
          try {
            scon.setSSLSocketFactory(SSLUtil.getSSLSocketFactory(clientCertAlias, trustAnyCert));
            HostnameVerifier hv = SSLUtil.getHostnameVerifier(hostCertLevel);
            if (hv != null) {
              scon.setHostnameVerifier(hv);
            }
          } catch (GeneralSecurityException e) {
            Debug.logError(e, module);
          } catch (GenericConfigException e) {
            Debug.logError(e, module);
          }
        }
      } catch (IOException e) {
        Debug.logError(e, module);
      }

      synchronized (URLConnector.this) {
        if (timedOut && con != null) {
          close(con);
        } else {
          connection = con;
          URLConnector.this.notify();
        }
      }
    }
Esempio n. 2
0
 private void parse(String fragment, ExpressionFactory expressionFactory) {
   Debug.logn("Parse Method Call " + fragment, this);
   this.name = fragment.substring(0, fragment.indexOf("(")).trim();
   String paramString = fragment.substring(1 + fragment.indexOf("("), fragment.lastIndexOf(")"));
   Debug.logn("-Params " + paramString, this);
   this.parseParamStrings(paramString, expressionFactory);
 }
  public void actionPerformed(ActionEvent e) {

    // --SEND/GET UPDATE(s) FROM SERVER-- Called whenever timer goes off (every 5 sec.)

    // ==== SEND ALL OF THE MESSAGES WE HAVE ====
    comm.sendOutboxMessages();
    // ==== SEND A REQUEST FOR A UNIVERSAL UPDATE ====
    comm.sendMessage("REQUEST");
    // ==== RECIEVE THE UNIVERSE/ROSTER/MARKET UPDATES ====
    ArrayList<String> responses = comm.getAllMessages();
    // ==== HERE IS WHERE WE UNPACK THE UPDATES FROM THE SERVER ====
    for (int q = 0; q < responses.size(); q++) {
      String header = responses.get(q).substring(0, 4);

      if (header.equals("UNIV")) {
        theUniverse.unpack(responses.get(q));
        Debug.msg("Unpacked a Universe");
        theDisplay.updateDisplay();
      } else if (header.equals("ROST")) {
        Roster.unpack(responses.get(q));
      } else if (header.equals("MARK")) {
        theMarket.unpack(responses.get(q));
      } else if (header.equals("SERV")) {
        Vector inParsed = ParseUtil.parseStringBySign(responses.get(q), '-');
        myPlayerNum = Integer.parseInt((String) inParsed.elementAt(1));
      } else Debug.msg("Unknown header recieved in ClientMain.actionPerformed() ");
    }
  }
Esempio n. 4
0
  private void cautiouslyApproachVisibleEnemySoldier(MapLocation enemySoldier, int maxEnemyExposure)
      throws GameActionException {
    int[] numEnemiesAttackingDirs = countNumEnemiesAttackingMoveDirs();

    Direction toEnemy = here.directionTo(enemySoldier);
    Direction[] tryDirs = new Direction[] {toEnemy, toEnemy.rotateLeft(), toEnemy.rotateRight()};
    for (int i = 0; i < tryDirs.length; i++) {
      Direction tryDir = tryDirs[i];
      if (!rc.canMove(tryDir)) continue;
      if (numEnemiesAttackingDirs[tryDir.ordinal()] > maxEnemyExposure) continue;
      if (Util.inHQAttackRange(here.add(tryDir), theirHQ)) continue;
      Debug.indicate(
          "micro",
          1,
          String.format(
              "cautiously approaching enemy soldier; direction %d; attackers = %d %d %d %d %d %d %d %d",
              tryDir.ordinal(),
              numEnemiesAttackingDirs[0],
              numEnemiesAttackingDirs[1],
              numEnemiesAttackingDirs[2],
              numEnemiesAttackingDirs[3],
              numEnemiesAttackingDirs[4],
              numEnemiesAttackingDirs[5],
              numEnemiesAttackingDirs[6],
              numEnemiesAttackingDirs[7]));
      rc.move(tryDir);
      return;
    }
    Debug.indicate("micro", 1, "can't safely approach enemy soldier");
  }
Esempio n. 5
0
  /**
   * Pretty-print debug function. Two equal <code>PAEscapeFunc</code>s are guaranteed to have the
   * same string representation.
   */
  public String toString() {
    StringBuffer buffer = new StringBuffer(" Escape function:\n");

    Set set = new HashSet(rel_n.keys());
    ////// set.addAll(escaped_into_mh);
    set.addAll(rel_m.keys());

    Object[] nodes = Debug.sortedSet(set);
    for (int i = 0; i < nodes.length; i++) {
      PANode n = (PANode) nodes[i];
      buffer.append("  " + n + ":");

      Object[] nholes = Debug.sortedSet(nodeHolesSet(n));
      for (int j = 0; j < nholes.length; j++) {
        buffer.append(" ");
        buffer.append((PANode) nholes[j]);
      }

      Object[] mholes = Debug.sortedSet(methodHolesSet(n));
      for (int j = 0; j < mholes.length; j++) {
        buffer.append("\n\t");
        buffer.append((HMethod) mholes[j]);
      }

      ///// if(escaped_into_mh.contains(n))
      /////	buffer.append(" M");
      buffer.append("\n");
    }

    return buffer.toString();
  }
Esempio n. 6
0
  public static void testEncode(String input, String encoding) throws XcodeException {
    String inputdecoded = null;
    String output = null;
    String variant = null;

    if (input == null) {
      Debug.pass("");
      return;
    }
    input = input.trim();

    if (input.length() == 0 || input.charAt(0) == '#') {
      Debug.pass(input);
      return;
    }

    try {
      inputdecoded = new String(Hex.decodeChars(input));
      output = Native.encode(inputdecoded, encoding);
    } catch (XcodeException x) {
      Debug.fail(input + "	ERROR:" + x.getCode() + "	" + x.getMessage());
      return;
    }

    System.out.println(Hex.encode(output.toCharArray()));
  }
Esempio n. 7
0
  /*
   * Get the active protocol versions.
   *
   * In TLS 1.1, many weak or vulnerable cipher suites were obsoleted,
   * such as TLS_RSA_EXPORT_WITH_RC4_40_MD5. The implementation MUST NOT
   * negotiate these cipher suites in TLS 1.1 or later mode.
   *
   * For example, if "TLS_RSA_EXPORT_WITH_RC4_40_MD5" is the
   * only enabled cipher suite, the client cannot request TLS 1.1 or
   * later, even though TLS 1.1 or later is enabled.  We need to create a
   * subset of the enabled protocols, called the active protocols, which
   * contains protocols appropriate to the list of enabled Ciphersuites.
   *
   * Return empty list instead of null if no active protocol versions.
   */
  ProtocolList getActiveProtocols() {
    if (activeProtocols == null) {
      ArrayList<ProtocolVersion> protocols = new ArrayList<>(4);
      for (ProtocolVersion protocol : enabledProtocols.collection()) {
        boolean found = false;
        for (CipherSuite suite : enabledCipherSuites.collection()) {
          if (suite.isAvailable()
              && suite.obsoleted > protocol.v
              && suite.supported <= protocol.v) {
            if (algorithmConstraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), suite.name, null)) {
              protocols.add(protocol);
              found = true;
              break;
            } else if (debug != null && Debug.isOn("verbose")) {
              System.out.println("Ignoring disabled cipher suite: " + suite + " for " + protocol);
            }
          } else if (debug != null && Debug.isOn("verbose")) {
            System.out.println("Ignoring unsupported cipher suite: " + suite + " for " + protocol);
          }
        }
        if (!found && (debug != null) && Debug.isOn("handshake")) {
          System.out.println("No available cipher suite for " + protocol);
        }
      }
      activeProtocols = new ProtocolList(protocols);
    }

    return activeProtocols;
  }
Esempio n. 8
0
  /* (non-Javadoc)
   * @see android.app.Activity#onCreate(android.os.Bundle)
   */
  @Override
  public void onCreate(Bundle savedState) {
    super.onCreate(savedState);
    Debug.print("onCreate()");
    try {
      MotionEventWrapper5.checkAvailable();
      Rokon.motionEvent5 = new MotionEventWrapper5();
    } catch (VerifyError e) {
    }

    try {
      MotionEventWrapper8.checkAvailable();
      Rokon.motionEvent8 = new MotionEventWrapper8();
    } catch (VerifyError e) {
    }
    if (engineCreated) {
      Debug.print("onCreate() when already started, creating new GLSurfaceView");
      // surfaceView = new RokonSurfaceView(this);
      // setContentView(surfaceView);
      return;
    }
    Debug.print("Engine Activity created");
    onCreate();
    if (!engineCreated) {
      Debug.error("The engine was not created");
      Debug.print("#################### FINISH ME HERE");
      finish();
      return;
    }
  }
Esempio n. 9
0
 @Override
 public void run() {
   Socket clientSocket = null;
   PrintWriter out = null;
   try {
     Debug.log(ReportServlet.SERVLET, "[NotifyUsers]: notifying user: "******";" + latitude + ";" + reportID);
     Debug.log(ReportServlet.SERVLET, "[NotifyUsers]: end notify user: " + clientAddress);
   } catch (UnknownHostException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (out != null) {
       out.close();
     }
     if (clientSocket != null) {
       try {
         clientSocket.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
Esempio n. 10
0
  public static String printKeyHash(Context context) {
    PackageInfo packageInfo;
    String key = null;
    try {
      // getting application package name, as defined in manifest
      String packageName = context.getPackageName();

      // Retriving package info
      packageInfo =
          context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);

      Debug.e("Package Name=" + context.getPackageName());

      for (Signature signature : packageInfo.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        key = new String(Base64.encode(md.digest(), 0));

        // String key = new String(Base64.encodeBytes(md.digest()));
        Debug.e("Key Hash=" + key);
      }
    } catch (PackageManager.NameNotFoundException e1) {
      Debug.e("Name not found" + e1.toString());
    } catch (NoSuchAlgorithmException e) {
      Debug.e("No such an algorithm" + e.toString());
    } catch (Exception e) {
      Debug.e("Exception" + e.toString());
    }

    return key;
  }
Esempio n. 11
0
  private void retreatOrFight() throws GameActionException {
    // If all our opponents have really high action delay, we can fire a last shot
    // and still be able to move before they can return fire. This would most probably
    // happen if an enemy engaged us after several diagonal moves. This could turn
    // a losing 1v1 into a winning one!
    boolean fireOneLastShot = true;
    for (int i = attackableEnemies.length; i-- > 0; ) {
      fireOneLastShot &= attackableEnemies[i].actionDelay >= 3;
      if (!fireOneLastShot) break;
    }

    if (fireOneLastShot) {
      Debug.indicate("micro", 2, "parthian shot");
      attackASoldier();
      return;
    }

    Direction dir = chooseRetreatDirection();
    if (dir == null) { // Can't retreat! Fight!
      Debug.indicate("micro", 2, "couldn't retreat; fighting instead");
      RobotInfo target = chooseSoldierAttackTarget(attackableEnemies);
      attackAndRecord(target);
    } else { // Can retreat. Do it!
      Debug.indicate("micro", 2, "retreating successfully");
      rc.move(dir);
    }
  }
Esempio n. 12
0
  // ---------------------------------------------------------------------------
  private void writeCache() {
    try {
      Debug.print("Writing cache");
      FileOutputStream fos = new FileOutputStream(m_cacheFile);
      ObjectOutputStream oos = new ObjectOutputStream(fos);

      oos.writeObject(m_depCache);

      oos.writeInt(m_newModificationCache.size());

      Iterator<String> it = m_newModificationCache.keySet().iterator();

      while (it.hasNext()) {
        String key = it.next();

        oos.writeUTF(key);
        oos.writeLong(m_newModificationCache.get(key));
      }

      oos.close();
    } catch (Exception e) {
      Debug.print(e.getMessage());
      StringWriter sw = new StringWriter();
      e.printStackTrace(new PrintWriter(sw));
      Debug.print(sw.toString());
    }
  }
Esempio n. 13
0
 public static void setVerboseLevel(int level) {
   debug.clearDebugSymbols();
   if (level >= 1) {
     debug.addDebugSymbol(Debug.DebugSymbol.SOLUTION_WHATISINSIDE);
   }
   if (level >= 2) {
     debug.addDebugSymbol(Debug.DebugSymbol.FIRST_LAST_STATES);
   }
   if (level >= 3) {
     debug.addDebugSymbol(Debug.DebugSymbol.SOLUTION_REDUCED);
   }
   if (level >= 4) {
     debug.addDebugSymbol(Debug.DebugSymbol.REACTIONS);
   }
   if (level >= 5) {
     debug.addDebugSymbol(Debug.DebugSymbol.REACTIONS_STATS);
   }
   if (level >= 6) {
     debug.addDebugSymbol(Debug.DebugSymbol.SOLUTION_PARTIAL);
   }
   if (level >= 7) {
     debug.addDebugSymbol(Debug.DebugSymbol.TESTED_PERM);
   }
   if (level >= 8) {
     debug.addDebugSymbol(Debug.DebugSymbol.STRATEGY);
   }
   if (level >= 9) {
     debug.addDebugSymbol(Debug.DebugSymbol.PERMUTATION);
   }
 }
Esempio n. 14
0
  /**
   * POSTs the given content to the given URL.
   *
   * @param String the url to post to
   * @param content the body of the post
   * @param contentType the content-type of the request
   * @exception IOException if post fails
   */
  public static String post(String urlString, String contentType, String content)
      throws IOException {

    Debug.log(
        Debug.MSG_LIFECYCLE,
        "HTTPUtils: Trying to post " + content + " to web server at [ " + urlString + "]");

    StringBuffer responseBuffer = new StringBuffer();

    URL url = new URL(urlString);

    ClientSocket cs = new ClientSocket();

    HTTPUtils.Response resp = post(cs, url, new Hashtable(), contentType, content);

    while (true) {
      String line = resp.content.readLine();
      if (line == null) break;

      responseBuffer.append(line);
    }

    Debug.log(
        Debug.MSG_LIFECYCLE,
        "HTTPUtils: Obtained response from web server : " + responseBuffer.toString());

    cleanUp(cs);

    return responseBuffer.toString();
  }
Esempio n. 15
0
  /**
   * propogate the next signal from self to all instances. Callers must be synchronized on 'this'
   * object.
   */
  public synchronized boolean propogateNextSignalSelf(Debug debugObject)
      throws LemRuntimeException {
    /*
     * First propogate any elapsed delayed signals to self
     * into the signalSelfQueue.
     */
    while (delayedSignalSelfQueue.size() > 0) {
      DelayedSignal s;
      s = (DelayedSignal) delayedSignalSelfQueue.get(0);
      if (s.getDeliveryTime() <= context.getTimeObject().getTimeMs()) {
        delayedSignalSelfQueue.remove(s);
        addSignalSelf(s);
      } else break;
    }

    if (signalSelfQueue.size() > 0) {
      Signal s = (Signal) signalSelfQueue.remove(0);
      for (Iterator i = instances.iterator(); i.hasNext(); ) {
        Instance in = (Instance) i.next();
        if (in.isActive) {
          in.addSignalSelf(s);
          debugObject.addEntity();
        }
      }
      debugObject.delEntity();
      return true;
    }

    return false;
  }
Esempio n. 16
0
  /**
   * Close all IO connections that were opened during post()
   *
   * @param cs Client socket items to populate.
   */
  private static void cleanUp(ClientSocket cs) throws IOException {

    Debug.log(Debug.MSG_LIFECYCLE, "HTTPUtils: closing IO socket connections");

    if (cs.in != null) {
      try {
        cs.in.close();

        cs.in = null;
      } catch (Exception e) {
        Debug.log(Debug.ALL_WARNINGS, e.toString());
      }
    }

    if (cs.out != null) {
      try {
        cs.out.close();

        cs.out = null;
      } catch (Exception e) {
        Debug.log(Debug.ALL_WARNINGS, e.toString());
      }
    }

    if (cs.s != null) {
      try {
        cs.s.close();

        cs.s = null;
      } catch (Exception e) {
        Debug.log(Debug.ALL_WARNINGS, e.toString());
      }
    }
  }
Esempio n. 17
0
  /**
   * This method loads properties in virtual machine.
   *
   * @param key - Ket value of persistentproperty.
   * @param type - Type value of persistentproperty.
   * @exception - ProcessingException - this exception is thrown by super class for any problem with
   *     initialization .
   */
  public void initialize(String key, String type) throws ProcessingException {
    Debug.log(this, Debug.DB_STATUS, "Loading properties for RTF generator.");
    super.initialize(key, type);

    nextProcessor = (String) adapterProperties.get(NEXT_PROCESSOR_NAME);
    startDelimiter = (String) adapterProperties.get(START_DELIMITER);
    endDelimiter = (String) adapterProperties.get(END_DELIMITER);
    rtfTemplate = (String) adapterProperties.get(RTF_TEMPLATE);

    if (nextProcessor == null
        || startDelimiter == null
        || endDelimiter == null
        || rtfTemplate == null
        || nextProcessor.equals("")
        || startDelimiter.equals("")
        || endDelimiter.equals("")
        || rtfTemplate.equals("")) {
      Debug.log(
          this,
          Debug.ALL_ERRORS,
          "ERROR: RTFGenerator: One or more RTF generator properties are missing.");
      throw new ProcessingException(
          "ERROR: RTFGenerator: One or more properties from persistentproperty"
              + " could not be loaded or are null");
    }
  }
Esempio n. 18
0
 // Returns -1 if there's an error.
 public static int getDistance(Position a, Position b) {
   if (a == null || b == null) return -1;
   Debug.assertTrue(a.getLine() != null);
   Debug.assertTrue(b.getLine() != null);
   if (a.equals(b)) return 0;
   Position pos, end;
   if (a.isBefore(b)) {
     pos = a.copy();
     end = b.copy();
   } else {
     pos = b.copy();
     end = a.copy();
   }
   final Line endLine = end.getLine();
   int distance = 0;
   while (pos.getLine() != endLine) {
     distance += (pos.getLineLength() + 1 - pos.getOffset());
     Line nextLine = pos.getNextLine();
     if (nextLine == null) return -1;
     pos.moveTo(nextLine, 0);
   }
   Debug.assertTrue(pos.getLine() == endLine);
   distance += end.getOffset() - pos.getOffset();
   return distance;
 }
Esempio n. 19
0
  public static Entry[] andNot(Entry[] a, Entry[] b) {
    if (Debug.ENABLED) {
      checkInvariants(a);
      checkInvariants(b);
    }

    if (Debug.ENABLED) { // Should not call for nothing
      boolean empty = true;

      for (int i = b.length - 1; i >= 0; i--) {
        if (b[i] != null) {
          Debug.assertion(b[i].Value != 0);
          empty = false;
        }
      }

      Debug.assertion(!empty);
    }

    Entry[] result = PlatformAdapter.createBitsArray(a.length);

    for (int i = a.length - 1; i >= 0; i--) if (a[i] != null) result[i] = andNot(a[i], b);

    return result;
  }
Esempio n. 20
0
  /**
   * Load the database from the database file given in "database.json" if the file doesn't exist, it
   * gets created here if the file has a database in it already, it is loaded here
   *
   * @return false if there is an error opening the database
   */
  public boolean open() {
    try {
      System.out.println(dbPath);
      File dbFile = new File(dbPath);

      // Only read the database from the file if it exists
      if (dbFile.exists()) {
        FileInputStream fileIn = new FileInputStream(dbPath);
        ObjectInputStream in = new ObjectInputStream(fileIn);
        // load the database here
        database = (HashMap<K, V>) in.readObject();
        // make sure the streams close properly
        in.close();
        fileIn.close();

        Debug.println("Database loaded");
      } else {
        dbFile.getParentFile().mkdirs();
        dbFile.createNewFile();

        Debug.println("Database created");
      }
      return true;
    } catch (Exception e) {
      System.err.println("Error opening database");
      System.err.println(e);
      return false;
    }
  }
Esempio n. 21
0
 /**
  * The timeout thread. If it wakes from the sleep, future input is stopped and the request is
  * timed out.
  */
 public final void run() {
   try {
     if (Debug.LDAP_DEBUG) {
       Debug.trace(
           Debug.messages,
           message.name + "client timer started, " + timeToWait + " milliseconds");
     }
     sleep(timeToWait);
     message.acceptReplies = false;
     if (Debug.LDAP_DEBUG) {
       Debug.trace(Debug.messages, message.name + "client timed out");
     }
     // Note: Abandon clears the bind semaphore after failed bind.
     message.abandon(
         null,
         new InterThreadException(
             "Client request timed out", null, LDAPException.LDAP_TIMEOUT, null, message));
   } catch (InterruptedException ie) {
     if (Debug.LDAP_DEBUG) {
       Debug.trace(Debug.messages, message.name + "timer stopped");
     }
     // the timer was stopped, do nothing
   }
   return;
 }
Esempio n. 22
0
  @Override
  public void uncaughtException(Thread arg0, Throwable arg1) {
    // 把错误的堆栈信息 获取出来
    String errorInfo = getErrorInfo(arg1);
    String uuidKey = UUID.nameUUIDFromBytes(errorInfo.getBytes()).toString();

    String existsException = Utils.getSharedPreferences("uncaughtException").getString(uuidKey, "");
    if (!existsException.equals("")) {
      // -- this uncaughtException has got
      Debug.Log("Exception has got yet: " + errorInfo);
      Debug.Log("kill self() ");
      android.os.Process.killProcess(android.os.Process.myPid());
      return;
    }

    Editor editor = Utils.getSharedPreferences("uncaughtException").edit();
    editor.putString(uuidKey, "Mark");
    editor.commit();

    String content = DeviceInfo.getInfo(context).toString();
    String msg = content + "\nStack:\n" + errorInfo;

    Debug.Log("uncaughtException: " + msg);

    errorContent = msg;

    //        sendExceptionMsg();
  }
Esempio n. 23
0
  /**
   * This function takes a perl5 regular expression as the pattern to perform pattern matching and
   * string substitution.
   *
   * <p>"s/pattern/replacement/[g][i][m][o][s][x]"
   *
   * <p>g - substitute globally (all occurence) i - case insensitive m - treat the input as
   * consisting of multiple lines o - interpolate once s - treat the input as consisting of a single
   * line x - enable extended expression syntax incorporating whitespace and comments
   *
   * <p>to perform string substitution. Unless the [g] option is specified, the dafault is to
   * replace only the first occurrence.
   *
   * @param perl5Pattern - Perl5 regular expression
   * @param input - input string
   * @return result - processed string. The original input is returned when there is no match
   * @exception - FrameworkException is thrown when either pattern or input is null
   */
  public static String substitute(String perl5Pattern, String input) throws FrameworkException {
    if ((perl5Pattern == null) || (input == null)) {
      throw new FrameworkException(
          "RegexUtil: replaceAll(): Either input or pattern is null."
              + "input = "
              + input
              + ", "
              + "pattern = "
              + perl5Pattern);
    }

    if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {
      Debug.log(
          Debug.MSG_STATUS,
          "RegexUtils: replaceAll: perl5Pattern = " + perl5Pattern + " input = " + input);
    }

    Perl5Util util = new Perl5Util();
    String result = input;

    try {
      result = util.substitute(perl5Pattern, input);
    } catch (RuntimeException e) {
      throw new FrameworkException("RegexUtils: substitute: " + e.getMessage());
    }

    return result;
  }
Esempio n. 24
0
 /* package */
 Object getReply() {
   Object msg;
   if (replies == null) {
     return null;
   }
   synchronized (replies) {
     // Test and remove must be atomic
     if (replies.isEmpty()) {
       if (Debug.LDAP_DEBUG) {
         Debug.trace(Debug.messages, name + "No replies queued for message");
       }
       return null; // No data
     }
     msg = replies.remove(0); // Atomic get and remove
   }
   if (Debug.LDAP_DEBUG) {
     Debug.trace(
         Debug.messages, name + "Got reply from queue(" + replies.size() + " remaining in queue)");
   }
   if ((conn != null) && (complete || !acceptReplies) && replies.isEmpty()) {
     // Remove msg from connection queue when last reply read
     conn.removeMessage(this);
   }
   return msg;
 }
Esempio n. 25
0
  /**
   * This function composes the perl regular expression to perform pattern matching with negative
   * look ahead. This becomes handy when a replacement string includes some string that is also a
   * pattern.
   *
   * <p>i.e.) pattern - & replacement - &quot, &amp
   *
   * @param pattern - pattern string to match
   * @param replacements - an array of replacement strings
   * @return returns the format pattern for perl5 negative look-ahead
   * @exception throws a FrameworkException when the pattern/replacement is null.
   */
  private static String makePerl5MatchPatternNegativeLookAhead(
      String pattern, String replacements[]) throws FrameworkException {
    if (pattern == null || replacements.length < 0) {
      throw new FrameworkException(
          "RegexUtils: makePerl5MatchPatternNegativeLookAhead: pattern or replacement is null."
              + "\npattern = "
              + pattern
              + "\nreplacements.length = "
              + replacements.length);
    }

    String result = null;
    StringBuffer patternBuffer = new StringBuffer();

    Perl5Util util = new Perl5Util();
    String formatPattern = makePerl5MatchPattern(pattern);

    for (int i = 0; i < replacements.length; i++) {
      if (util.match(formatPattern, replacements[i])) {
        if (replacements[i].startsWith(pattern)) {
          result = util.postMatch();

          // very first one
          if (i == 0) {
            patternBuffer.append(pattern);
            patternBuffer.append("(?!");
          }
          patternBuffer.append(result);

          // the last one
          if (i == (replacements.length - 1)) {
            patternBuffer.append(")");
          } else // not the last one, cat the perl5 separater
          {
            patternBuffer.append("|");
          }

        } else {
          throw new FrameworkException(
              "ERROR: RegexUtils: makePerl5MatchPatternNegativeLookAhead: The pattern in the "
                  + "replacement string should be at the beginning.");
        }
      } else // no match found meaning invalid use of this function
      {
        throw new FrameworkException(
            "ERROR: RegexUtils: makePerl5MatchPatternNegativeLookAhead: "
                + "Invalid use of the function.");
      }
    }

    if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {
      Debug.log(
          Debug.MSG_STATUS,
          "RegexUtils: makePerl5MatchPatternNegativeLookAhead: patternBuffer.toString() = "
              + patternBuffer.toString());
    }

    return patternBuffer.toString();
  }
 static Generic[][] compute(Generic generic[], Variable unknown[]) {
   Linearization l = new Linearization(unknown);
   Debug.println("linearization");
   Debug.increment();
   l.process(generic);
   Debug.decrement();
   return l.getValue();
 }
Esempio n. 27
0
  public BotSoldier(RobotController theRC) throws GameActionException {
    super(theRC);
    Debug.init(theRC, "micro");
    Nav.init(theRC);

    spawnOrder = MessageBoard.SPAWN_COUNT.readInt();
    Debug.indicate("buildorder", 0, "I am robot #" + spawnOrder);
  }
Esempio n. 28
0
 public X509Certificate[] getCertificateChain(String alias) {
   X509Certificate[] certArray = keyManager.getCertificateChain(alias);
   if (Debug.verboseOn())
     Debug.logVerbose(
         "getCertificateChain for alias [" + alias + "] got " + certArray.length + " results",
         module);
   return certArray;
 }
Esempio n. 29
0
  final void assertIdle() {
    if (!Debug.ENABLED) throw new IllegalStateException();

    if (_writes != null)
      for (int i = 0; i < _writes.length; i++) Debug.assertion(_writes[i] == null);

    Debug.assertion(_happenedBefore == null);
  }
Esempio n. 30
0
  public void actionPerformed(ActionEvent event) {
    if (Debug.isActive()) Debug.println("Action for Collapse Tree button");

    tree_view.collapseLevel();
    toolbar.getYaxisTreeCommitButton().doClick();

    // Set toolbar buttons to reflect status
    toolbar.resetYaxisTreeButtons();
  }