/** Does the specified ReferenceType match this spec. */
 @Override
 public boolean matches(ReferenceType refType) {
   if (isWild) {
     return refType.name().endsWith(classId);
   } else {
     return refType.name().equals(classId);
   }
 }
Пример #2
0
  public static ReferenceType getSuperClass(
      final String baseQualifiedName, ReferenceType checkedType) {
    if (baseQualifiedName.equals(checkedType.name())) {
      return checkedType;
    }

    if (checkedType instanceof ClassType) {
      ClassType classType = (ClassType) checkedType;
      ClassType superClassType = classType.superclass();
      if (superClassType != null) {
        ReferenceType superClass = getSuperClass(baseQualifiedName, superClassType);
        if (superClass != null) {
          return superClass;
        }
      }
      List<InterfaceType> interfaces = classType.allInterfaces();
      for (InterfaceType iface : interfaces) {
        ReferenceType superClass = getSuperClass(baseQualifiedName, iface);
        if (superClass != null) {
          return superClass;
        }
      }
    }

    if (checkedType instanceof InterfaceType) {
      List<InterfaceType> list = ((InterfaceType) checkedType).superinterfaces();
      for (InterfaceType superInterface : list) {
        ReferenceType superClass = getSuperClass(baseQualifiedName, superInterface);
        if (superClass != null) {
          return superClass;
        }
      }
    }
    return null;
  }
Пример #3
0
 static ReferenceType getReferenceTypeFromToken(String idToken) {
   ReferenceType cls = null;
   if (Character.isDigit(idToken.charAt(0))) {
     cls = null;
   } else if (idToken.startsWith("*.")) {
     // This notation saves typing by letting the user omit leading
     // package names. The first
     // loaded class whose name matches this limited regular
     // expression is selected.
     idToken = idToken.substring(1);
     for (ReferenceType type : Env.vm().allClasses()) {
       if (type.name().endsWith(idToken)) {
         cls = type;
         break;
       }
     }
   } else {
     // It's a class name
     List<ReferenceType> classes = Env.vm().classesByName(idToken);
     if (classes.size() > 0) {
       // TO DO: handle multiples
       cls = classes.get(0);
     }
   }
   return cls;
 }
Пример #4
0
 protected static String calcLabel(ValueDescriptor descriptor) {
   final ValueDescriptorImpl valueDescriptor = (ValueDescriptorImpl) descriptor;
   final Value value = valueDescriptor.getValue();
   if (value instanceof ObjectReference) {
     if (value instanceof StringReference) {
       return ((StringReference) value).value();
     } else if (value instanceof ClassObjectReference) {
       ReferenceType type = ((ClassObjectReference) value).reflectedType();
       return (type != null) ? type.name() : "{...}";
     } else {
       final ObjectReference objRef = (ObjectReference) value;
       final Type type = objRef.type();
       if (type instanceof ClassType && ((ClassType) type).isEnum()) {
         final String name = getEnumConstantName(objRef, (ClassType) type);
         if (name != null) {
           return name;
         } else {
           return type.name();
         }
       } else {
         return "";
       }
     }
   } else if (value == null) {
     //noinspection HardCodedStringLiteral
     return "null";
   } else {
     return DebuggerBundle.message("label.undefined");
   }
 }
Пример #5
0
  public void exceptionEvent(ExceptionEvent event) {
    ObjectReference or = event.exception();
    ReferenceType rt = or.referenceType();
    String exceptionName = rt.name();
    // Field messageField = Throwable.class.getField("detailMessage");
    Field messageField = rt.fieldByName("detailMessage");
    //    System.out.println("field " + messageField);
    Value messageValue = or.getValue(messageField);
    //    System.out.println("mess val " + messageValue);

    // "java.lang.ArrayIndexOutOfBoundsException"
    int last = exceptionName.lastIndexOf('.');
    String message = exceptionName.substring(last + 1);
    if (messageValue != null) {
      String messageStr = messageValue.toString();
      if (messageStr.startsWith("\"")) {
        messageStr = messageStr.substring(1, messageStr.length() - 1);
      }
      message += ": " + messageStr;
    }
    //    System.out.println("mess type " + messageValue.type());
    // StringReference messageReference = (StringReference) messageValue.type();

    // First just report the exception and its placement
    reportException(message, or, event.thread());
    // Then try to pretty it up with a better message
    handleCommonErrors(exceptionName, message, listener);

    if (editor != null) {
      editor.deactivateRun();
    }
  }
Пример #6
0
 private void commandClasses() throws NoSessionException {
   OutputSink out = env.getOutputSink();
   // out.println("** classes list **");
   for (ReferenceType refType : runtime.allClasses()) {
     out.println(refType.name());
   }
   out.show();
 }
Пример #7
0
 public static String getLocationMethodQName(@NotNull Location location) {
   StringBuilder res = new StringBuilder();
   ReferenceType type = location.declaringType();
   if (type != null) {
     res.append(type.name()).append('.');
   }
   res.append(location.method().name());
   return res.toString();
 }
Пример #8
0
 /** Return a description of an object. */
 static String description(ObjectReference ref) {
   ReferenceType clazz = ref.referenceType();
   long id = ref.uniqueID();
   if (clazz == null) {
     return toHex(id);
   } else {
     return MessageOutput.format(
         "object description and hex id", new Object[] {clazz.name(), toHex(id)});
   }
 }
Пример #9
0
 @Override
 protected boolean createRequest(JDXDebugTarget target, ReferenceType type) throws CoreException {
   if (!type.name().equals(getTypeName()) || shouldSkipBreakpoint()) {
     return false;
   }
   EventRequest entryRequest = createMethodEntryRequest(target, type);
   EventRequest exitRequest = createMethodExitRequest(target, type);
   registerRequest(entryRequest, target);
   registerRequest(exitRequest, target);
   return true;
 }
Пример #10
0
 /**
  * Return a list of ReferenceType objects for all currently loaded classes and interfaces whose
  * name matches the given pattern. The pattern syntax is open to some future revision, but
  * currently consists of a fully-qualified class name in which the first component may optionally
  * be a "*" character, designating an arbitrary prefix.
  */
 public List findClassesMatchingPattern(String pattern) throws JDEException {
   if (vm == null) return null;
   List result = new ArrayList(); // ### Is default size OK?
   if (pattern.startsWith("*.")) {
     // Wildcard matches any leading package name.
     pattern = pattern.substring(1);
     List classes = vm.allClasses();
     Iterator iter = classes.iterator();
     while (iter.hasNext()) {
       ReferenceType type = ((ReferenceType) iter.next());
       if (type.name().endsWith(pattern)) {
         result.add(type);
       }
     }
     return result;
   } else {
     // It's a class name.
     return vm.classesByName(pattern);
   }
 }
Пример #11
0
 /** Does the specified ReferenceType match this spec. */
 public boolean matches(ReferenceType refType) {
   String refName = refType.name().replace('$', '.');
   String compName;
   compName = refName;
   if (anonymous) {
     String anonymousBase = anonymousBaseName(refName);
     if (anonymousBase != null) compName = anonymousBase;
     else return false;
   }
   if (classId.startsWith("*")) {
     return compName.endsWith(stem);
   } else if (classId.endsWith("*")) {
     return compName.startsWith(stem);
   } else if (checkJavaLang
       && compName.startsWith("java.lang.")
       && compName.substring(10).equals(stem)) {
     return true;
   } else {
     return compName.equals(transClassId);
   }
 }
Пример #12
0
 private void dump(
     OutputSink out, ObjectReference obj, ReferenceType refType, ReferenceType refTypeBase) {
   for (Field field : refType.fields()) {
     out.print("    ");
     if (!refType.equals(refTypeBase)) {
       out.print(refType.name() + ".");
     }
     out.print(field.name() + ": ");
     Object o = obj.getValue(field);
     out.println((o == null) ? "null" : o.toString()); // Bug ID 4374471
   }
   if (refType instanceof ClassType) {
     ClassType sup = ((ClassType) refType).superclass();
     if (sup != null) {
       dump(out, obj, sup, refTypeBase);
     }
   } else if (refType instanceof InterfaceType) {
     for (InterfaceType sup : ((InterfaceType) refType).superinterfaces()) {
       dump(out, obj, sup, refTypeBase);
     }
   }
 }
Пример #13
0
 /** Get source object associated with a class or interface. Returns null if not available. */
 public SourceModel sourceForClass(ReferenceType refType) {
   SourceModel sm = classToSource.get(refType);
   if (sm != null) {
     return sm;
   }
   try {
     String filename = refType.sourceName();
     String refName = refType.name();
     int iDot = refName.lastIndexOf('.');
     String pkgName = (iDot >= 0) ? refName.substring(0, iDot + 1) : "";
     String full = pkgName.replace('.', File.separatorChar) + filename;
     File path = sourcePath.resolve(full);
     if (path != null) {
       sm = sourceForFile(path);
       classToSource.put(refType, sm);
       return sm;
     }
     return null;
   } catch (AbsentInformationException e) {
     return null;
   }
 }
Пример #14
0
 @Override
 protected void createRequestForPreparedClass(
     DebugVMEventsProcessor debugProcess, final ReferenceType classType) {
   RequestManager requestManager = debugProcess.getRequestManager();
   try {
     int lineIndex = myLocation.getLineIndexInFile();
     List<Location> locs = classType.locationsOfLine(lineIndex);
     if (locs.size() > 0) {
       for (final Location location : locs) {
         BreakpointRequest request = requestManager.createBreakpointRequest(this, location);
         requestManager.enableRequest(request);
       }
     } else {
       //  there's no executable code in this class
       requestManager.setInvalid(this, "no executable code found");
       String message =
           "No locations of type "
               + classType.name()
               + " found at line "
               + myLocation.getLineIndexInFile();
       LOG.warning(message);
     }
   } catch (ClassNotPreparedException ex) {
     LOG.warning("ClassNotPreparedException: " + ex.getMessage());
     //  there's a chance to add a breakpoint when the class is prepared
   } catch (ObjectCollectedException ex) {
     LOG.warning("ObjectCollectedException: " + ex.getMessage());
     //  there's a chance to add a breakpoint when the class is prepared
   } catch (InvalidLineNumberException ex) {
     requestManager.setInvalid(this, "no executable code found");
     LOG.warning("InvalidLineNumberException: " + ex.getMessage());
   } catch (InternalException ex) {
     LOG.error(ex);
   } catch (Exception ex) {
     LOG.error(ex);
   }
 }
Пример #15
0
  public boolean run(String codeSnippetClassName) {
    ClassType codeSnippetClass;
    ObjectReference codeSnippet;
    Method method;
    List arguments;
    ObjectReference codeSnippetRunner;
    try {
      // Get the code snippet class
      List classes = jdiVM.classesByName(codeSnippetClassName);
      while (classes.size() == 0) {
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
        }
        classes = jdiVM.classesByName(codeSnippetClassName);
        if (classes.size() == 0) {
          // workaround bug in Standard VM
          Iterator iterator = this.jdiVM.allClasses().iterator();
          while (iterator.hasNext()) {
            ReferenceType type = (ReferenceType) iterator.next();
            if (type.name().equals(codeSnippetClassName)) {
              classes = new ArrayList(1);
              classes.add(type);
              break;
            }
          }
        }
      }
      codeSnippetClass = (ClassType) classes.get(0);

      // Create a new code snippet
      Method constructor = (Method) codeSnippetClass.methodsByName("<init>").get(0);
      codeSnippet =
          codeSnippetClass.newInstance(
              jdiThread, constructor, new ArrayList(), ClassType.INVOKE_SINGLE_THREADED);

      // Install local variables and "this" into generated fields
      StackFrame stackFrame = getStackFrame();
      try {
        Iterator variables = stackFrame.visibleVariables().iterator();
        while (variables.hasNext()) {
          LocalVariable jdiVariable = (LocalVariable) variables.next();
          Value value = stackFrame.getValue(jdiVariable);
          Field field =
              codeSnippetClass.fieldByName(new String(LOCAL_VAR_PREFIX) + jdiVariable.name());
          codeSnippet.setValue(field, value);
        }
      } catch (AbsentInformationException e) {
        // No variables
      }
      Field delegateThis = codeSnippetClass.fieldByName(new String(DELEGATE_THIS));
      ObjectReference thisObject;
      if (delegateThis != null && ((thisObject = stackFrame.thisObject()) != null)) {
        codeSnippet.setValue(delegateThis, thisObject);
      }

      // Get the code snippet runner
      ClassType codeSnippetRunnerClass =
          (ClassType) jdiVM.classesByName(CODE_SNIPPET_RUNNER_CLASS_NAME).get(0);
      Field theRunner = codeSnippetRunnerClass.fieldByName(THE_RUNNER_FIELD);
      codeSnippetRunner = (ObjectReference) codeSnippetRunnerClass.getValue(theRunner);

      // Get the method 'runCodeSnippet' and its arguments
      method = (Method) codeSnippetRunnerClass.methodsByName(RUN_CODE_SNIPPET_METHOD).get(0);
      arguments = new ArrayList();
      arguments.add(codeSnippet);
    } catch (ClassNotLoadedException e) {
      e.printStackTrace();
      return false;
    } catch (IncompatibleThreadStateException e) {
      e.printStackTrace();
      return false;
    } catch (InvalidTypeException e) {
      e.printStackTrace();
      return false;
    } catch (InvocationException e) {
      e.printStackTrace();
      return false;
    }

    try {
      // Invoke runCodeSnippet(CodeSnippet)
      codeSnippetRunner.invokeMethod(
          jdiThread, method, arguments, ClassType.INVOKE_SINGLE_THREADED);

      // Retrieve values of local variables and put them back in the stack frame
      StackFrame stackFrame = getStackFrame();
      try {
        Iterator variables = stackFrame.visibleVariables().iterator();
        while (variables.hasNext()) {
          LocalVariable jdiVariable = (LocalVariable) variables.next();
          Field field =
              codeSnippetClass.fieldByName(new String(LOCAL_VAR_PREFIX) + jdiVariable.name());
          Value value = codeSnippet.getValue(field);
          stackFrame.setValue(jdiVariable, value);
        }
      } catch (AbsentInformationException e) {
        // No variables
      }
    } catch (ClassNotLoadedException e) {
      e.printStackTrace();
    } catch (IncompatibleThreadStateException e) {
      e.printStackTrace();
    } catch (InvalidTypeException e) {
      e.printStackTrace();
    } catch (InvocationException e) {
      e.printStackTrace();
    }
    return true;
  }
  // copied from FrameVariablesTree
  private void buildVariables(
      DebuggerContextImpl debuggerContext,
      final EvaluationContextImpl evaluationContext,
      @NotNull DebugProcessImpl debugProcess,
      XValueChildrenList children,
      ObjectReference thisObjectReference,
      Location location)
      throws EvaluateException {
    final Set<String> visibleLocals = new HashSet<String>();
    if (NodeRendererSettings.getInstance().getClassRenderer().SHOW_VAL_FIELDS_AS_LOCAL_VARIABLES) {
      if (thisObjectReference != null
          && debugProcess.getVirtualMachineProxy().canGetSyntheticAttribute()) {
        final ReferenceType thisRefType = thisObjectReference.referenceType();
        if (thisRefType instanceof ClassType
            && location != null
            && thisRefType.equals(location.declaringType())
            && thisRefType.name().contains("$")) { // makes sense for nested classes only
          for (Field field : thisRefType.fields()) {
            if (DebuggerUtils.isSynthetic(field)
                && StringUtil.startsWith(
                    field.name(), FieldDescriptorImpl.OUTER_LOCAL_VAR_FIELD_PREFIX)) {
              final FieldDescriptorImpl fieldDescriptor =
                  myNodeManager.getFieldDescriptor(myDescriptor, thisObjectReference, field);
              children.add(JavaValue.create(fieldDescriptor, evaluationContext, myNodeManager));
              visibleLocals.add(fieldDescriptor.calcValueName());
            }
          }
        }
      }
    }

    boolean myAutoWatchMode = DebuggerSettings.getInstance().AUTO_VARIABLES_MODE;
    if (evaluationContext == null) {
      return;
    }
    final SourcePosition sourcePosition = debuggerContext.getSourcePosition();
    if (sourcePosition == null) {
      return;
    }

    try {
      if (!XDebuggerSettingsManager.getInstance().getDataViewSettings().isAutoExpressions()
          && !myAutoWatchMode) {
        // optimization
        superBuildVariables(evaluationContext, children);
      } else {
        final Map<String, LocalVariableProxyImpl> visibleVariables =
            getVisibleVariables(getStackFrameProxy());
        final Pair<Set<String>, Set<TextWithImports>> usedVars =
            ApplicationManager.getApplication()
                .runReadAction(
                    new Computable<Pair<Set<String>, Set<TextWithImports>>>() {
                      @Override
                      public Pair<Set<String>, Set<TextWithImports>> compute() {
                        return findReferencedVars(
                            ContainerUtil.union(visibleVariables.keySet(), visibleLocals),
                            sourcePosition);
                      }
                    });
        // add locals
        if (myAutoWatchMode) {
          for (String var : usedVars.first) {
            LocalVariableProxyImpl local = visibleVariables.get(var);
            if (local != null) {
              children.add(
                  JavaValue.create(
                      myNodeManager.getLocalVariableDescriptor(null, local),
                      evaluationContext,
                      myNodeManager));
            }
          }
        } else {
          superBuildVariables(evaluationContext, children);
        }
        final EvaluationContextImpl evalContextCopy =
            evaluationContext.createEvaluationContext(evaluationContext.getThisObject());
        evalContextCopy.setAutoLoadClasses(false);

        final Set<TextWithImports> extraVars =
            computeExtraVars(usedVars, sourcePosition, evaluationContext);

        // add extra vars
        addToChildrenFrom(extraVars, children, evaluationContext);

        // add expressions
        addToChildrenFrom(usedVars.second, children, evalContextCopy);
      }
    } catch (EvaluateException e) {
      if (e.getCause() instanceof AbsentInformationException) {
        children.add(
            new DummyMessageValueNode(
                MessageDescriptor.LOCAL_VARIABLES_INFO_UNAVAILABLE.getLabel(),
                XDebuggerUIConstants.INFORMATION_MESSAGE_ICON));
        // trying to collect values from variable slots
        try {
          for (Map.Entry<DecompiledLocalVariable, Value> entry :
              LocalVariablesUtil.fetchValues(getStackFrameProxy(), debugProcess).entrySet()) {
            children.add(
                JavaValue.create(
                    myNodeManager.getArgumentValueDescriptor(
                        null, entry.getKey(), entry.getValue()),
                    evaluationContext,
                    myNodeManager));
          }
        } catch (Exception ex) {
          LOG.info(ex);
        }
      } else {
        throw e;
      }
    }
  }
Пример #17
0
  protected ThreadReference getDebuggedThread(DebugEvaluationTest test) {
    try {
      // desintall previous breakpoints
      this.jdiVM.eventRequestManager().deleteAllBreakpoints();

      // install a breakpoint at the breakpointLine
      List classes = this.jdiVM.classesByName(this.breakpointClassName);
      if (classes.size() == 0) {
        if (this.breakpointClassName.equals("_JDIStackFrame_")) {
          // install special class
          String source =
              "public class _JDIStackFrame_ {\n"
                  + "  public int foo() {\n"
                  + "    return -1;\n"
                  + "  }\n"
                  + "}";
          test.compileAndDeploy(source, "_JDIStackFrame_");
        }

        // force load of class
        test.evaluateWithExpectedDisplayString(
            ("return Class.forName(\"" + this.breakpointClassName + "\");").toCharArray(),
            ("class " + this.breakpointClassName).toCharArray());
        classes = this.jdiVM.classesByName(this.breakpointClassName);
        if (classes.size() == 0) {
          // workaround bug in Standard VM
          Iterator iterator = this.jdiVM.allClasses().iterator();
          while (iterator.hasNext()) {
            ReferenceType type = (ReferenceType) iterator.next();
            if (type.name().equals(this.breakpointClassName)) {
              classes = new ArrayList(1);
              classes.add(type);
              break;
            }
          }
          if (classes.size() == 0) {
            throw new Error("JDI could not retrieve class for " + this.breakpointClassName);
          }
        }
      }
      ClassType clazz = (ClassType) classes.get(0);
      Method method = (Method) clazz.methodsByName(this.breakpointMethodName).get(0);
      Location location;
      if (this.breakpointLine < 0 || this.breakpointLine == Integer.MAX_VALUE) {
        location = method.location();
      } else {
        location = (Location) method.locationsOfLine(this.breakpointLine).get(0);
      }
      BreakpointRequest request =
          this.jdiVM.eventRequestManager().createBreakpointRequest(location);
      request.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
      request.enable();

      // create a new thread that hit the breakpoint
      EvaluationTest.Requestor requestor = test.new Requestor();
      try {
        test.resetEnv();
        test.context.evaluate(
            ("(new Thread() {\n"
                    + "  public void run() {\n"
                    + userCode
                    + "\n"
                    + (this.breakpointClassName.equals("_JDIStackFrame_")
                        ? "    new _JDIStackFrame_().foo();\n"
                        : "")
                    + "  }\n"
                    + "  public String toString() {\n"
                    + "    return \"my thread\";\n"
                    + "  }\n"
                    + "}).start();\n")
                .toCharArray(),
            test.getEnv(),
            test.getCompilerOptions(),
            requestor,
            test.getProblemFactory());
      } catch (InstallException e) {
        Assert.assertTrue("Target exception " + e.getMessage(), false);
      }
      EvaluationResult[] results = requestor.results;
      for (int i = 0; i < requestor.resultIndex + 1; i++) {
        if (results[i].hasErrors()) {
          Assert.assertTrue("Compilation error in user code", false);
        }
      }

      // Wait for the breakpoint event
      Event event = null;
      do {
        EventSet set = this.jdiVM.eventQueue().remove();
        Iterator iterator = set.eventIterator();
        while (iterator.hasNext()) {
          event = (Event) iterator.next();
          if (event instanceof BreakpointEvent) break;
        }
      } while (!(event instanceof BreakpointEvent));

      // Return the suspended thread
      return ((BreakpointEvent) event).thread();
    } catch (AbsentInformationException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return null;
  }
Пример #18
0
  private static void checkReferenceType(ReferenceType valueType, ReferenceType type)
      throws InvalidTypeException {
    if (valueType instanceof ArrayType) {
      if (type instanceof ArrayType) {
        try {
          Type valueComponentType = ((ArrayType) valueType).componentType();
          Type componentType = ((ArrayType) type).componentType();
          if (valueComponentType instanceof PrimitiveType) {
            if (valueComponentType.equals(componentType)) {
              return;
            }
          } else if (valueComponentType instanceof ReferenceType
              && componentType instanceof ReferenceType) {
            checkReferenceType((ReferenceType) valueComponentType, (ReferenceType) componentType);
            return;
          }
        } catch (ClassNotLoadedException e) {
          // should not append
        }
      } else {
        // an array can be assigned to an object
        if (type.signature().equals("Ljava/lang/Object;")) { // $NON-NLS-1$
          return;
        }
      }
    } else {
      if (type instanceof ClassType) {
        if (valueType instanceof ClassType) {
          ClassType superClass = (ClassType) valueType;
          while (superClass != null) {
            if (superClass.equals(type)) {
              return;
            }
            superClass = superClass.superclass();
          }
        } else if (valueType instanceof InterfaceType) {
          // an interface can be assigned to an object
          if (type.signature().equals("Ljava/lang/Object;")) { // $NON-NLS-1$
            return;
          }
        }
      } else if (type instanceof InterfaceType) {
        if (valueType instanceof InterfaceType) {
          if (checkInterfaceType((InterfaceType) valueType, (InterfaceType) type)) {
            return;
          }
        } else {
          List<InterfaceType> interfaces = ((ClassType) valueType).allInterfaces();
          for (Iterator<InterfaceType> iter = interfaces.iterator(); iter.hasNext(); ) {
            if (checkInterfaceType(iter.next(), (InterfaceType) type)) {
              return;
            }
          }
        }
      }
    }

    throw new InvalidTypeException(
        MessageFormat.format(
            JDIMessages.ValueImpl_Type_of_the_value_not_compatible_with_the_expected_type__1,
            new Object[] {valueType.name(), type.name()}));
  }
Пример #19
0
 private void commandList(StringTokenizer t) throws NoSessionException {
   ThreadReference current = context.getCurrentThread();
   if (current == null) {
     env.error("No thread specified.");
     return;
   }
   Location loc;
   try {
     StackFrame frame = context.getCurrentFrame(current);
     if (frame == null) {
       env.failure("Thread has not yet begun execution.");
       return;
     }
     loc = frame.location();
   } catch (VMNotInterruptedException e) {
     env.failure("Target VM must be in interrupted state.");
     return;
   }
   SourceModel source = sourceManager.sourceForLocation(loc);
   if (source == null) {
     if (loc.method().isNative()) {
       env.failure("Current method is native.");
       return;
     }
     env.failure("No source available for " + Utils.locationString(loc) + ".");
     return;
   }
   ReferenceType refType = loc.declaringType();
   int lineno = loc.lineNumber();
   if (t.hasMoreTokens()) {
     String id = t.nextToken();
     // See if token is a line number.
     try {
       lineno = Integer.valueOf(id).intValue();
     } catch (NumberFormatException nfe) {
       // It isn't -- see if it's a method name.
       List<Method> meths = refType.methodsByName(id);
       if (meths == null || meths.size() == 0) {
         env.failure(
             id + " is not a valid line number or " + "method name for class " + refType.name());
         return;
       } else if (meths.size() > 1) {
         env.failure(id + " is an ambiguous method name in" + refType.name());
         return;
       }
       loc = meths.get(0).location();
       lineno = loc.lineNumber();
     }
   }
   int startLine = (lineno > 4) ? lineno - 4 : 1;
   int endLine = startLine + 9;
   String sourceLine = source.sourceLine(lineno);
   if (sourceLine == null) {
     env.failure("" + lineno + " is an invalid line number for " + refType.name());
   } else {
     OutputSink out = env.getOutputSink();
     for (int i = startLine; i <= endLine; i++) {
       sourceLine = source.sourceLine(i);
       if (sourceLine == null) {
         break;
       }
       out.print(i);
       out.print("\t");
       if (i == lineno) {
         out.print("=> ");
       } else {
         out.print("   ");
       }
       out.println(sourceLine);
     }
     out.show();
   }
 }
 @Override
 protected void createRequestForPreparedClass(
     final DebugProcessImpl debugProcess, final ReferenceType classType) {
   if (!isInScopeOf(debugProcess, classType.name())) {
     if (LOG.isDebugEnabled()) {
       LOG.debug(
           classType.name()
               + " is out of debug-process scope, breakpoint request won't be created for line "
               + getLineIndex());
     }
     return;
   }
   try {
     List<Location> locations =
         debugProcess.getPositionManager().locationsOfLine(classType, getSourcePosition());
     if (!locations.isEmpty()) {
       for (Location loc : locations) {
         if (LOG.isDebugEnabled()) {
           LOG.debug(
               "Found location [codeIndex="
                   + loc.codeIndex()
                   + "] for reference type "
                   + classType.name()
                   + " at line "
                   + getLineIndex()
                   + "; isObsolete: "
                   + (debugProcess.getVirtualMachineProxy().versionHigher("1.4")
                       && loc.method().isObsolete()));
         }
         if (!acceptLocation(debugProcess, classType, loc)) {
           continue;
         }
         final BreakpointRequest request =
             debugProcess.getRequestsManager().createBreakpointRequest(this, loc);
         debugProcess.getRequestsManager().enableRequest(request);
         if (LOG.isDebugEnabled()) {
           LOG.debug(
               "Created breakpoint request for reference type "
                   + classType.name()
                   + " at line "
                   + getLineIndex()
                   + "; codeIndex="
                   + loc.codeIndex());
         }
       }
     } else {
       // there's no executable code in this class
       debugProcess
           .getRequestsManager()
           .setInvalid(
               this,
               DebuggerBundle.message(
                   "error.invalid.breakpoint.no.executable.code",
                   (getLineIndex() + 1),
                   classType.name()));
       if (LOG.isDebugEnabled()) {
         LOG.debug(
             "No locations of type " + classType.name() + " found at line " + getLineIndex());
       }
     }
   } catch (ClassNotPreparedException ex) {
     if (LOG.isDebugEnabled()) {
       LOG.debug("ClassNotPreparedException: " + ex.getMessage());
     }
     // there's a chance to add a breakpoint when the class is prepared
   } catch (ObjectCollectedException ex) {
     if (LOG.isDebugEnabled()) {
       LOG.debug("ObjectCollectedException: " + ex.getMessage());
     }
     // there's a chance to add a breakpoint when the class is prepared
   } catch (InvalidLineNumberException ex) {
     if (LOG.isDebugEnabled()) {
       LOG.debug("InvalidLineNumberException: " + ex.getMessage());
     }
     debugProcess
         .getRequestsManager()
         .setInvalid(this, DebuggerBundle.message("error.invalid.breakpoint.bad.line.number"));
   } catch (InternalException ex) {
     LOG.info(ex);
   } catch (Exception ex) {
     LOG.info(ex);
   }
   updateUI();
 }
 private static boolean isAnonymousClass(ReferenceType classType) {
   if (classType instanceof ClassType) {
     return ourAnonymousPattern.matcher(classType.name()).matches();
   }
   return false;
 }