Пример #1
1
 /**
  * Register the device to Google Cloud Messaging service or return registration id if it's already
  * registered.
  *
  * @return registration id or empty string if it's not registered.
  */
 private static String gcmRegisterIfNot(Context context) {
   String regId = "";
   try {
     GCMRegistrar.checkDevice(context);
     GCMRegistrar.checkManifest(context);
     regId = GCMRegistrar.getRegistrationId(context);
     String gcmId = BuildConfig.GCM_ID;
     if (gcmId != null && TextUtils.isEmpty(regId)) {
       GCMRegistrar.register(context, gcmId);
     }
   } catch (UnsupportedOperationException e) {
     // GCMRegistrar.checkDevice throws an UnsupportedOperationException if the device
     // doesn't support GCM (ie. non-google Android)
     AppLog.e(T.NOTIFS, "Device doesn't support GCM: " + e.getMessage());
   } catch (IllegalStateException e) {
     // GCMRegistrar.checkManifest or GCMRegistrar.register throws an IllegalStateException if
     // Manifest
     // configuration is incorrect (missing a permission for instance) or if GCM dependencies are
     // missing
     AppLog.e(
         T.NOTIFS,
         "APK (manifest error or dependency missing) doesn't support GCM: " + e.getMessage());
   } catch (Exception e) {
     // SecurityException can happen on some devices without Google services (these devices
     // probably strip
     // the AndroidManifest.xml and remove unsupported permissions).
     AppLog.e(T.NOTIFS, e);
   }
   return regId;
 }
  public void testMaliciousGetIcons() {
    Iterable<WWIcon> icons = createExampleIterable();

    IconLayer layer = new IconLayer();
    layer.addIcons(icons);

    Iterable<WWIcon> layerIcons = layer.getIcons();

    // Test that the returned list cannot be modified.
    try {
      if (layerIcons instanceof java.util.Collection) {
        java.util.Collection<WWIcon> collection = (java.util.Collection<WWIcon>) layerIcons;
        collection.clear();
      } else {
        java.util.Iterator<WWIcon> iter = layerIcons.iterator();
        while (iter.hasNext()) {
          iter.next();
          iter.remove();
        }
      }
    } catch (UnsupportedOperationException e) {
      e.printStackTrace();
    }

    // Test that the layer contents do not change, even if the returned list can be modified.
    assertEquals("", icons, layerIcons);
  }
 private void setPriceLevel(int len) {
   try {
     gspaContainer.setPriceLevel(GspaContainer.EPriceLevel.getPriceLevelFromInt(len));
   } catch (UnsupportedOperationException e) {
     log(ELog.e, e.getMessage(), e);
   }
 }
Пример #4
0
  /**
   * Returns the identifying type of this Advertisement. Unlike {@link #getAdvertisementType()} this
   * method will return the correct runtime type of an Advertisement object.
   *
   * <p>This implementation is provided for existing advertisements which do not provide their own
   * implementation. In most cases you should provide your own implementation for efficiency
   * reasons.
   *
   * @since JXSE 2.1.1
   * @return The identifying type of this Advertisement.
   */
  public String getAdvType() {
    try {
      Method getAdvertisementTypeMethod =
          this.getClass().getMethod("getAdvertisementType", (Class[]) null);
      String result = (String) getAdvertisementTypeMethod.invoke(null, (Object[]) null);

      return result;
    } catch (NoSuchMethodException failed) {
      UnsupportedOperationException failure =
          new UnsupportedOperationException("Could not get Advertisement type.");

      failure.initCause(failed);
      throw failure;
    } catch (IllegalAccessException failed) {
      SecurityException failure = new SecurityException("Could not get Advertisement type.");

      failure.initCause(failed);
      throw failure;
    } catch (InvocationTargetException failed) {
      UndeclaredThrowableException failure =
          new UndeclaredThrowableException(failed, "Failed getting Advertisement type.");

      failure.initCause(failed.getCause());
      throw failure;
    }
  }
Пример #5
0
  /**
   * Translates the equalities of the given symbolic constraint into SMTLib format. Ignores the
   * substitution of the symbolic constraint.
   */
  @Override
  public ASTNode transform(SymbolicConstraint constraint) {
    if (constraint.data.equalities.isEmpty()) {
      return new SMTLibTerm("true");
    }

    StringBuilder sb = new StringBuilder();
    sb.append("(and");
    boolean isEmptyAdd = true;
    for (SymbolicConstraint.Equality equality : constraint.data.equalities) {
      try {
        String left = ((SMTLibTerm) equality.leftHandSide().accept(this)).expression();
        String right = ((SMTLibTerm) equality.rightHandSide().accept(this)).expression();
        sb.append(" (= ");
        sb.append(left);
        sb.append(" ");
        sb.append(right);
        sb.append(")");
        isEmptyAdd = false;
      } catch (UnsupportedOperationException e) {
        // TODO(AndreiS): fix this translation and the exceptions
        if (skipEqualities) {
          /* it is sound to skip the equalities that cannot be translated */
          e.printStackTrace();
        } else {
          throw e;
        }
      }
    }
    if (isEmptyAdd) {
      sb.append(" true");
    }
    sb.append(")");
    return new SMTLibTerm(sb.toString());
  }
  @Test
  public void testDeleteUnsupportedQueryType() throws Exception {
    final Schema schema = dataContext.getDefaultSchema();
    final CreateTable createTable = new CreateTable(schema, "testCreateTable");
    createTable.withColumn("foo").ofType(ColumnType.STRING);
    createTable.withColumn("bar").ofType(ColumnType.NUMBER);
    dataContext.executeUpdate(createTable);

    final Table table = schema.getTableByName("testCreateTable");
    try {

      dataContext.executeUpdate(
          new UpdateScript() {
            @Override
            public void run(UpdateCallback callback) {
              callback.insertInto(table).value("foo", "hello").value("bar", 42).execute();
              callback.insertInto(table).value("foo", "world").value("bar", 43).execute();
            }
          });

      // greater than is not yet supported
      try {
        dataContext.executeUpdate(new DeleteFrom(table).where("bar").gt(40));
        fail("Exception expected");
      } catch (UnsupportedOperationException e) {
        assertEquals(
            "Could not push down WHERE items to delete by query request: [testCreateTable.bar > 40]",
            e.getMessage());
      }

    } finally {
      dataContext.executeUpdate(new DropTable(table));
    }
  }
Пример #7
0
  /** Closes the write half of the stream. */
  @Override
  public void closeWrite() throws IOException {
    if (_isCloseWrite) {
      return;
    }

    _isCloseWrite = true;

    // OutputStream os = _os;
    // _os = null;

    boolean isShutdownOutput = false;

    // since the output stream is opened lazily, we might
    // need to open it
    if (_s != null) {
      try {
        _s.shutdownOutput();

        isShutdownOutput = true;
      } catch (UnsupportedOperationException e) {
        log.log(Level.FINEST, e.toString(), e);
      } catch (Exception e) {
        log.finer(e.toString());
        log.log(Level.FINEST, e.toString(), e);
      }
    }

    /*
    // SSLSocket doesn't support shutdownOutput()
    if (! isShutdownOutput && os != null) {
      os.close();
    }
    */
  }
Пример #8
0
 @Restricted(DoNotUse.class) // accessed via REST API
 public HttpResponse doGenerateSnippet(StaplerRequest req, @QueryParameter String json)
     throws Exception {
   // TODO JENKINS-31458 is there not an easier way to do this?
   JSONObject jsonO = JSONObject.fromObject(json);
   Jenkins j = Jenkins.getActiveInstance();
   Class<?> c = j.getPluginManager().uberClassLoader.loadClass(jsonO.getString("stapler-class"));
   StepDescriptor descriptor = (StepDescriptor) j.getDescriptor(c.asSubclass(Step.class));
   Object o;
   try {
     o = descriptor.newInstance(req, jsonO);
   } catch (RuntimeException x) { // e.g. IllegalArgumentException
     return HttpResponses.plainText(Functions.printThrowable(x));
   }
   try {
     String groovy = object2Groovy(o);
     if (descriptor.isAdvanced()) {
       String warning = Messages.Snippetizer_this_step_should_not_normally_be_used_in();
       groovy = "// " + warning + "\n" + groovy;
     }
     return HttpResponses.plainText(groovy);
   } catch (UnsupportedOperationException x) {
     Logger.getLogger(CpsFlowExecution.class.getName())
         .log(Level.WARNING, "failed to render " + json, x);
     return HttpResponses.plainText(x.getMessage());
   }
 }
Пример #9
0
 public static void raiseError(String message) {
   try {
     throw new UnsupportedOperationException(message);
   } catch (UnsupportedOperationException e) {
     System.out.println(e.getStackTrace());
   }
 }
Пример #10
0
 private static void test(File file, Format format) throws IOException {
   testWriting(file, format);
   try {
     testReading(file);
   } catch (UnsupportedOperationException e) {
     e.printStackTrace();
   }
 }
Пример #11
0
 protected String makeDaemon() {
   try {
     NativeCalls.getInstance().daemonize(null);
   } catch (UnsupportedOperationException e) {
     return "WARNING: " + e.getMessage();
   } catch (IllegalStateException ignored) {
   }
   return null;
 }
Пример #12
0
 @Test
 public void test_unsupported() {
   try {
     factory.build(-1);
     fail();
   } catch (UnsupportedOperationException err) {
     assertEquals("Unsupported form field type", err.getMessage());
   }
 }
 public void testNamedWriteableNotSupportedWithoutWrapping() throws IOException {
   BytesStreamOutput out = new BytesStreamOutput();
   TestNamedWriteable testNamedWriteable = new TestNamedWriteable("test1", "test2");
   out.writeNamedWriteable(testNamedWriteable);
   StreamInput in = StreamInput.wrap(BytesReference.toBytes(out.bytes()));
   try {
     in.readNamedWriteable(BaseNamedWriteable.class);
     fail("Expected UnsupportedOperationException");
   } catch (UnsupportedOperationException e) {
     assertThat(e.getMessage(), is("can't read named writeable from StreamInput"));
   }
 }
Пример #14
0
  /**
   * Constructs a new prover with the given <code>SymbolTable</code> and sets it immediately to work
   * on the verification conditions represented in the provided <code>Collection</code> of <code>
   * AssertiveCode</code>. If this constructor returns without throwing an exception, the VCs have
   * been proved. Otherwise, an exception is thrown indicating which VC could not be proved (or was
   * proved inconsistent).
   *
   * @param symbolTable The current symbol table. May not be <code>null</code>.
   * @param vCs A list of verification conditions in the form of <code>AssertiveCode</code>. May not
   *     be <code>null</code>.
   * @param maxDepth The maximum length of proof the prover should consider.
   * @throws UnableToProveException If a given VC cannot be proved in a reasonable amount of time.
   * @throws VCInconsistentException If a given VC can be proved inconsistent.
   * @throes NullPointerException If <code>symbolTable</code> or <code>vC</code> is <code>null
   *     </code>.
   */
  public Prover(
      final MathExpTypeResolver typer,
      final Iterable<VerificationCondition> vCs,
      final CompileEnvironment instanceEnvironment)
      throws ProverException {

    if (instanceEnvironment.flags.isFlagSet(FLAG_TIMEOUT)) {
      TIMEOUT =
          Long.parseLong(
              instanceEnvironment.flags.getFlagArgument(FLAG_TIMEOUT, FLAG_TIMEOUT_ARG_NAME));
    } else {
      TIMEOUT = Integer.MAX_VALUE;
    }

    myInstanceEnvironment = instanceEnvironment;

    allProved = true;

    if (!myInstanceEnvironment.flags.isFlagSet(FLAG_NOGUI)) {
      myProgressWindow = new ProofProgressWindow("VC", null);
    }

    myTyper = typer;
    buildTheories();

    try {
      proveVCs(vCs);

      CompileReport myReport = myInstanceEnvironment.getCompileReport();
      if (!myReport.hasError() && allProved) {
        myReport.setProveSuccess();
      }
    } catch (UnsupportedOperationException e) {
      // Exp.equivalent() is not consistently implemented throughout the
      // absyn package. By default, it will just throw an
      // UnsupportedOperationException if it is called and has not been
      // overridden. This will catch this case and produce a useful
      // error message.

      // On the other hand, it's sometimes useful for debugging to see a
      // full stack trace. Uncomment this next line to see that instead:
      if (true) throw new RuntimeException(e);

      ErrorHandler handler = myInstanceEnvironment.getErrorHandler();
      handler.error(e.getMessage() + "\n\nTry disabling the -prove option.");
    }

    if (!myInstanceEnvironment.flags.isFlagSet(FLAG_NOGUI)) {
      myProgressWindow.dispose();
    }
  }
 @Override
 public void execute(String[] args) {
   if (!tableIsSelected()) {
     return;
   }
   int deletedChanges = 0;
   try {
     deletedChanges = state.databaseAdapter.rollback();
   } catch (UnsupportedOperationException e) {
     state.printErrorMessage(e.getMessage());
     return;
   }
   state.printUserMessage(String.valueOf(deletedChanges));
 }
Пример #16
0
 private void rewindToEndActionPerformed(
     java.awt.event.ActionEvent evt) // GEN-FIRST:event_rewindToEndActionPerformed
     { // GEN-HEADEREND:event_rewindToEndActionPerformed
   try {
     Game activeGame = this.getActiveTabGame();
     if (!activeGame.rewindToEnd()) {
       JOptionPane.showMessageDialog(null, Settings.lang("noMoreUndoMovesInMemory"));
     }
   } catch (ArrayIndexOutOfBoundsException exc) {
     JOptionPane.showMessageDialog(null, Settings.lang("activeTabDoesNotExists"));
   } catch (UnsupportedOperationException exc) {
     JOptionPane.showMessageDialog(null, exc.getMessage());
   }
 } // GEN-LAST:event_rewindToEndActionPerformed
Пример #17
0
 @Override
 public Void visitLong(Property<Long> property, AbstractModel data) {
   try {
     Long value = data.getValue(property);
     String valueString = (value == null) ? XML_NULL : value.toString();
     xml.attribute(null, property.name, valueString);
   } catch (UnsupportedOperationException e) {
     // didn't read this value, do nothing
     Timber.e(e, e.getMessage());
   } catch (IllegalArgumentException | IOException | IllegalStateException e) {
     throw new RuntimeException(e);
   }
   return null;
 }
 public void printVegetarianMenu() {
   Iterator iterator = allMenus.createIterator();
   System.out.println("\nVEGETARIAN MENU\n-----");
   while (iterator.hasNext()) {
     MenuComponent menuComponent = (MenuComponent) iterator.next();
     try {
       if (menuComponent.isVegetarian()) {
         menuComponent.print();
       }
     } catch (UnsupportedOperationException e) {
       e.printStackTrace();
     }
   }
 }
 @Deprecated
 public List<?> getEntities(EntityReference ref, Search search) {
   // get the pollId
   Restriction pollRes = search.getRestrictionByProperty("pollId");
   if (pollRes == null || pollRes.getSingleValue() == null) {
     throw new IllegalArgumentException(
         "Must include a non-null pollId in order to retreive a list of votes");
   }
   Long pollId = null;
   try {
     pollId = developerHelperService.convert(pollRes.getSingleValue(), Long.class);
   } catch (UnsupportedOperationException e) {
     throw new IllegalArgumentException(
         "Invalid: pollId must be a long number: " + e.getMessage(), e);
   }
   // get the poll
   Poll poll = pollListManager.getPollById(pollId);
   if (poll == null) {
     throw new IllegalArgumentException(
         "pollId (" + pollId + ") is invalid and does not match any known polls");
   } else {
     boolean allowedPublic = pollListManager.isPollPublic(poll);
     if (!allowedPublic) {
       String userReference = developerHelperService.getCurrentUserReference();
       if (userReference == null) {
         throw new EntityException(
             "User must be logged in in order to access poll data",
             ref.getId(),
             HttpServletResponse.SC_UNAUTHORIZED);
       } else {
         boolean allowedManage = false;
         boolean allowedVote = false;
         allowedManage =
             developerHelperService.isUserAllowedInEntityReference(
                 userReference, PollListManager.PERMISSION_ADD, "/site/" + poll.getSiteId());
         allowedVote =
             developerHelperService.isUserAllowedInEntityReference(
                 userReference, PollListManager.PERMISSION_VOTE, "/site/" + poll.getSiteId());
         if (!(allowedManage || allowedVote)) {
           throw new SecurityException(
               "User (" + userReference + ") not allowed to access poll data: " + ref);
         }
       }
     }
   }
   // get the options
   List<Option> options = pollListManager.getOptionsForPoll(pollId);
   return options;
 }
Пример #20
0
 /** Checks if {@code left => right}, or {@code left /\ !right} is unsat. */
 public boolean impliesSMT(
     ConjunctiveFormula left, ConjunctiveFormula right, Set<Variable> rightOnlyVariables) {
   if (smtOptions.smt == SMTSolver.Z3) {
     try {
       return z3.isUnsat(
           KILtoSMTLib.translateImplication(left, right, rightOnlyVariables),
           smtOptions.z3ImplTimeout);
     } catch (UnsupportedOperationException e) {
       e.printStackTrace();
     } catch (SMTTranslationFailure e) {
       e.printStackTrace();
     }
   }
   return false;
 }
Пример #21
0
  /** Make sure we can actually fetch a MAC address. */
  @Test
  public void verifyMac() {
    byte[] mac;
    try {
      mac = MacUtils.macAddress();
    } catch (UnsupportedOperationException e) {
      // hmm... maybe we have no valid MAC's?
      e.printStackTrace();
      System.setProperty(MacUtils.OVERRIDE_MAC_PROP, "00:DE:AD:BE:EF:00");
      mac = MacUtils.macAddress();
    }

    Assert.assertNotNull("Could not retrieve MAC", mac);
    Assert.assertTrue("Invalid MAC address", mac.length == 6);
  }
  public void testMustRewrite() throws Exception {
    String templateString = "{ \"file\": \"storedTemplate\" ,\"params\":{\"template\":\"all\" } } ";

    XContentParser templateSourceParser =
        XContentFactory.xContent(templateString).createParser(templateString);
    context.reset();
    templateSourceParser.nextToken();
    try {
      TemplateQueryBuilder.fromXContent(context.newParseContext(templateSourceParser))
          .toQuery(context);
      fail();
    } catch (UnsupportedOperationException ex) {
      assertEquals("this query must be rewritten first", ex.getMessage());
    }
  }
 public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
   switch (7) {
     case 7:
       try {
         throw new UnsupportedOperationException();
       } catch (UnsupportedOperationException exceptUnsupportedOperation) {
         exceptUnsupportedOperation.printStackTrace(
             response.getWriter()); /* FLAW: Print stack trace in response on error */
       }
       break;
     default:
       /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
       IO.writeLine("Benign, fixed string");
       break;
   }
 }
  /** Tests NaturalIdReadOnlyCoherenceRegionAccessStrategy.update(). */
  @Test
  public void testUpdate() {
    try {
      NaturalIdRegionAccessStrategy accessStrategy = getNaturalIdRegionAccessStrategy();

      Object key = "testUpdate";
      Object value = "testUpdate";

      accessStrategy.update(key, value);
      fail("Expect CacheException updating read-only access strategy");
    } catch (UnsupportedOperationException ex) {
      assertEquals(
          "Expect writes not supported message",
          CoherenceRegionAccessStrategy.WRITE_OPERATIONS_NOT_SUPPORTED_MESSAGE,
          ex.getMessage());
    }
  }
Пример #25
0
  public void openLink(String link) {
    if (WWUtil.isEmpty(link)) return;

    try {
      try {
        // See if the link is a URL, and invoke the browser if it is
        URL url = new URL(link.replace(" ", "%20"));
        Desktop.getDesktop().browse(url.toURI());
        return;
      } catch (MalformedURLException ignored) { // just means that the link is not a URL
      }

      // It's not a URL, so see if it's a file and invoke the desktop to open it if it is.
      File file = new File(link);
      if (file.exists()) {
        Desktop.getDesktop().open(new File(link));
        return;
      }

      String message = "Cannot open resource. It's not a valid file or URL.";
      Util.getLogger().log(Level.SEVERE, message);
      this.showErrorDialog(null, "No Reconocido V\u00ednculo", message);
    } catch (UnsupportedOperationException e) {
      String message =
          "Unable to open resource.\n"
              + link
              + (e.getMessage() != null ? "\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message, e);
      this.showErrorDialog(e, "Error Opening Resource", message);
    } catch (IOException e) {
      String message =
          "I/O error while opening resource.\n"
              + link
              + (e.getMessage() != null ? ".\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message, e);
      this.showErrorDialog(e, "I/O Error", message);
    } catch (Exception e) {
      String message =
          "Error attempting to open resource.\n"
              + link
              + (e.getMessage() != null ? "\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message);
      this.showMessageDialog(message, "Error Opening Resource", JOptionPane.ERROR_MESSAGE);
    }
  }
Пример #26
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
      return;
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    String userID;
    String itemID;
    try {
      userID = pathComponents.next();
      itemID = pathComponents.next();
    } catch (NoSuchElementException nsee) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
      return;
    }
    if (pathComponents.hasNext()) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Path too long");
      return;
    }

    userID = unescapeSlashHack(userID);
    itemID = unescapeSlashHack(itemID);

    OryxRecommender recommender = getRecommender();
    try {
      output(
          request,
          response,
          recommender.recommendedBecause(userID, itemID, getNumResultsToFetch(request)));
    } catch (NoSuchUserException nsue) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND, nsue.toString());
    } catch (NoSuchItemException nsie) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    } catch (NotReadyException nre) {
      response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (IllegalArgumentException iae) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
    } catch (UnsupportedOperationException uoe) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, uoe.toString());
    }
  }
Пример #27
0
 private void moveBackItemActionPerformed(
     java.awt.event.ActionEvent evt) // GEN-FIRST:event_moveBackItemActionPerformed
     { // GEN-HEADEREND:event_moveBackItemActionPerformed
   if (getGui() != null && getGui().getGame() != null) {
     getGui().getGame().undo();
   } else {
     try {
       Game activeGame = this.getActiveTabGame();
       if (!activeGame.undo()) {
         JOptionPane.showMessageDialog(null, Settings.lang("noMoreUndoMovesInMemory"));
       }
     } catch (java.lang.ArrayIndexOutOfBoundsException exc) {
       JOptionPane.showMessageDialog(null, Settings.lang("activeTabDoesNotExists"));
     } catch (UnsupportedOperationException exc) {
       JOptionPane.showMessageDialog(null, exc.getMessage());
     }
   }
 } // GEN-LAST:event_moveBackItemActionPerformed
 @Override
 public ErrorResponse toErrorResponse(UnsupportedOperationException exception) {
   ErrorData error = ErrorData.builder().setDetail(exception.getMessage()).build();
   List<ErrorData> errors = Collections.singletonList(error);
   return ErrorResponse.builder() //
       .setStatus(FORBIDDEN_403) //
       .setErrorData(errors)
       .build();
 }
Пример #29
0
  @Test
  public void shouldUseSpecifiedJavacJar() throws Exception {
    BuildRuleResolver resolver = new BuildRuleResolver();
    SourcePathResolver pathResolver = new SourcePathResolver(resolver);
    BuildRule rule = new FakeBuildRule("//:fake", pathResolver);
    resolver.addToIndex(rule);

    Path fakeJavacJar = Paths.get("ae036e57-77a7-4356-a79c-0f85b1a3290d", "fakeJavac.jar");
    ExecutionContext executionContext = TestExecutionContext.newInstance();
    MockClassLoader mockClassLoader =
        new MockClassLoader(
            ClassLoader.getSystemClassLoader(),
            ImmutableMap.<String, Class<?>>of(
                "com.sun.tools.javac.api.JavacTool", MockJavac.class));
    executionContext
        .getClassLoaderCache()
        .injectClassLoader(
            ClassLoader.getSystemClassLoader(),
            ImmutableList.of(fakeJavacJar.toUri().toURL()),
            mockClassLoader);

    Jsr199Javac javac = createJavac(/* withSyntaxError */ false, Optional.of(fakeJavacJar));

    boolean caught = false;

    try {
      javac.buildWithClasspath(
          executionContext,
          createProjectFilesystem(),
          PATH_RESOLVER,
          BuildTargetFactory.newInstance("//some:example"),
          ImmutableList.<String>of(),
          SOURCE_PATHS,
          Optional.of(pathToSrcsList),
          Optional.<Path>absent());
      fail("Did not expect compilation to succeed");
    } catch (UnsupportedOperationException ex) {
      if (ex.toString().contains("abcdef")) {
        caught = true;
      }
    }

    assertTrue("mock Java compiler should throw", caught);
  }
Пример #30
0
 public void addMessToVectorInSortedOrder(Vector v, MhrEvent ev) {
   ListIterator iter = v.listIterator();
   MhrEvent vEv;
   while (iter.hasNext()) {
     vEv = (MhrEvent) iter.next();
     if (ev.eventTime.compareTo(vEv.eventTime) >= 0) {
       iter.previous();
       iter.add(ev);
       return;
     }
   }
   try {
     iter.add(ev);
   } catch (UnsupportedOperationException e) {
     System.out.println(e.toString());
   } catch (Exception e) {
     System.out.println(e.toString());
   }
 }