Ejemplo n.º 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;
 }
  @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));
    }
  }
Ejemplo n.º 3
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());
   }
 }
 private void setPriceLevel(int len) {
   try {
     gspaContainer.setPriceLevel(GspaContainer.EPriceLevel.getPriceLevelFromInt(len));
   } catch (UnsupportedOperationException e) {
     log(ELog.e, e.getMessage(), e);
   }
 }
Ejemplo n.º 5
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);
    }
  }
 @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();
 }
Ejemplo n.º 7
0
 protected String makeDaemon() {
   try {
     NativeCalls.getInstance().daemonize(null);
   } catch (UnsupportedOperationException e) {
     return "WARNING: " + e.getMessage();
   } catch (IllegalStateException ignored) {
   }
   return null;
 }
Ejemplo n.º 8
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"));
   }
 }
Ejemplo n.º 10
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();
    }
  }
Ejemplo n.º 11
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
Ejemplo n.º 12
0
 @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));
 }
Ejemplo n.º 13
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;
 }
 @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;
 }
  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());
    }
  }
  /** 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());
    }
  }
Ejemplo n.º 17
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
Ejemplo n.º 18
0
  protected String getRankingOutput(ServiceTemplate template) {
    List<Service> services;
    String result = "";
    try {
      if (registeredWebServices != null) {
        services = this.rank(registeredWebServices, template);

        if (services.isEmpty()) {
          result = "No web services to rank";
        } else {
          result = "\nThe ranked set of Web services is:\n";
          for (Service s : services) result += s.resource + "\n";
        }
      }
    } catch (UnsupportedOperationException e) {
      logger.warn("Operation not supported.", e);
      return "Operation not supported: " + e.getMessage();
    }

    return result;
  }
Ejemplo n.º 19
0
  private double doFunction(int beg, int end) {
    int argbeg;

    for (argbeg = beg; argbeg <= end && expression.charAt(argbeg) != '('; argbeg++) {;
    }

    String fncnam = expression.substring(beg, argbeg).trim();
    ArgParser fncargs = new ArgParser(argbeg, end);
    FunctionHandler fnchdl = null;

    try {
      if ((fnchdl = pureFunctions.get(fncnam)) != null) {
        return fnchdl.evaluateFunction(fncnam, fncargs);
      } else if ((fnchdl = impureFunctions.get(fncnam)) != null) {
        isConstant = false; // impure functions cannot be guaranteed to be constant
        return fnchdl.evaluateFunction(fncnam, fncargs);
      }
      fncargs = null; // suppress check for too many fncargs
    } catch (ArithmeticException thr) {
      fncargs = null;
      throw thr;
    } catch (NoSuchMethodError thr) {
      fncargs = null;
      throw exception(beg, "Function not supported in this JVM: \"" + fncnam + "\"");
    } catch (UnsupportedOperationException thr) {
      fncargs = null;
      throw exception(beg, thr.getMessage());
    } catch (Throwable thr) {
      fncargs = null;
      throw exception(beg, "Unexpected exception parsing function arguments", thr);
    } finally {
      if (fncargs != null) {
        if (fncargs.hasNext()) {
          throw exception(fncargs.getIndex(), "Function has too many arguments");
        }
        offset = fncargs.getIndex();
      }
    }
    throw exception(beg, "Function \"" + fncnam + "\" not recognized");
  }
Ejemplo n.º 20
0
  public static void main(String[] args) throws RecommenderBuildException {
    LenskitConfiguration config = configureRecommender();

    logger.info("building recommender");
    Recommender rec = LenskitRecommender.build(config);

    if (args.length == 0) {
      logger.error("No users specified; provide user IDs as command line arguments");
    }

    // we automatically get a useful recommender since we have a scorer
    ItemRecommender irec = rec.getItemRecommender();
    assert irec != null;
    try {
      // Generate 5 recommendations for each user
      for (String user : args) {
        long uid;
        try {
          uid = Long.parseLong(user);
        } catch (NumberFormatException e) {
          logger.error("cannot parse user {}", user);
          continue;
        }
        logger.info("searching for recommendations for user {}", user);
        List<ScoredId> recs = irec.recommend(uid, 5);
        if (recs.isEmpty()) {
          logger.warn("no recommendations for user {}, do they exist?", uid);
        }
        System.out.format("recommendations for user %d:\n", uid);
        for (ScoredId id : recs) {
          System.out.format("  %d: %.4f\n", id.getId(), id.getScore());
        }
      }
    } catch (UnsupportedOperationException e) {
      if (e.getMessage().equals("stub implementation")) {
        System.out.println("Congratulations, the stub builds and runs!");
      }
    }
  }
Ejemplo n.º 21
0
  @Override
  public List<Privilege> query(QueryRequest request) throws EntitlementException {
    QueryFilter queryFilter = request.getQueryFilter();
    if (queryFilter == null) {
      // Return everything
      queryFilter = QueryFilter.alwaysTrue();
    }

    try {
      Set<SearchFilter> searchFilters =
          queryFilter.accept(
              new PrivilegeQueryBuilder(queryAttributes), new HashSet<SearchFilter>());

      return privilegeManager.search(searchFilters);
    } catch (UnsupportedOperationException ex) {
      throw new EntitlementException(
          EntitlementException.INVALID_SEARCH_FILTER, new Object[] {ex.getMessage()});
    } catch (IllegalArgumentException ex) {
      throw new EntitlementException(
          EntitlementException.INVALID_VALUE, new Object[] {ex.getMessage()});
    }
  }
  public void testIterateStatement() {
    epService
        .getEPAdministrator()
        .createEPL("create context PartitionedByString partition by theString from SupportBean");
    String[] fields = "c0,c1".split(",");
    EPStatement stmt =
        epService
            .getEPAdministrator()
            .createEPL(
                "@Name('StmtOne') context PartitionedByString select context.key1 as c0, sum(intPrimitive) as c1 from SupportBean.win:length(5)");

    epService.getEPRuntime().sendEvent(new SupportBean("E1", 10));
    epService.getEPRuntime().sendEvent(new SupportBean("E2", 20));
    epService.getEPRuntime().sendEvent(new SupportBean("E2", 21));

    Object[][] expectedAll = new Object[][] {{"E1", 10}, {"E2", 41}};
    EPAssertionUtil.assertPropsPerRow(stmt.iterator(), stmt.safeIterator(), fields, expectedAll);

    // test iterator ALL
    ContextPartitionSelector selector = ContextPartitionSelectorAll.INSTANCE;
    EPAssertionUtil.assertPropsPerRow(
        stmt.iterator(selector), stmt.safeIterator(selector), fields, expectedAll);

    // test iterator by context partition id
    selector = new SupportSelectorById(new HashSet<Integer>(Arrays.asList(0, 1, 2)));
    EPAssertionUtil.assertPropsPerRow(
        stmt.iterator(selector), stmt.safeIterator(selector), fields, expectedAll);

    selector = new SupportSelectorById(new HashSet<Integer>(Arrays.asList(1)));
    EPAssertionUtil.assertPropsPerRow(
        stmt.iterator(selector), stmt.safeIterator(selector), fields, new Object[][] {{"E2", 41}});

    assertFalse(stmt.iterator(new SupportSelectorById(Collections.<Integer>emptySet())).hasNext());
    assertFalse(stmt.iterator(new SupportSelectorById(null)).hasNext());

    try {
      stmt.iterator(null);
      fail();
    } catch (IllegalArgumentException ex) {
      assertEquals(ex.getMessage(), "No selector provided");
    }

    try {
      stmt.safeIterator(null);
      fail();
    } catch (IllegalArgumentException ex) {
      assertEquals(ex.getMessage(), "No selector provided");
    }

    EPStatement stmtTwo =
        epService.getEPAdministrator().createEPL("select * from java.lang.Object");
    try {
      stmtTwo.iterator(null);
      fail();
    } catch (UnsupportedOperationException ex) {
      assertEquals(
          ex.getMessage(),
          "Iterator with context selector is only supported for statements under context");
    }

    try {
      stmtTwo.safeIterator(null);
      fail();
    } catch (UnsupportedOperationException ex) {
      assertEquals(
          ex.getMessage(),
          "Iterator with context selector is only supported for statements under context");
    }
  }
Ejemplo n.º 23
0
  public void render(Graphics2D destination, Envelope bounds, IProgressMonitor monitor)
      throws RenderException {
    WMTPlugin.trace("[BasicWMTRender.render] is called"); // $NON-NLS-1$

    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    monitor.beginTask("Render WMT", 100); // $NON-NLS-1$
    setState(STARTING);

    ILayer layer = null;
    try {
      layer = getContext().getLayer();
      // assume everything will work fine
      layer.setStatus(ILayer.DONE);
      layer.setStatusMessage(""); // $NON-NLS-1$

      WMTSource wmtSource = getWmtSourceFromLayer(layer);

      if (wmtSource == null)
        throw new UnsupportedOperationException(Messages.Render_Error_NoSource);

      // Layer properties
      WMTLayerProperties layerProperties =
          new WMTLayerProperties((StyleBlackboard) layer.getStyleBlackboard());

      // Get map extent, which should be drawn
      ReferencedEnvelope mapExtent = getRenderBounds();
      if (mapExtent == null) {
        mapExtent = context.getViewportModel().getBounds();
      }

      // Scale
      double scale = getContext().getViewportModel().getScaleDenominator();
      WMTPlugin.trace("[BasicWMTRender.render] Scale: " + scale); // $NON-NLS-1$

      WMTRenderJob renderJob = null;
      try {
        renderJob = WMTRenderJob.createRenderJob(mapExtent, scale, wmtSource);
      } catch (Exception exc) {
        throw new UnsupportedOperationException(Messages.Render_Error_Projection);
      }

      // Find tiles
      Map<String, Tile> tileList =
          wmtSource.cutExtentIntoTiles(
              renderJob, WMTRenderJob.getScaleFactor(), false, layerProperties);

      // if we have nothing to display, return
      if (tileList.isEmpty()) {
        throw new UnsupportedOperationException(Messages.Render_Error_NoData);
      }

      // check if this are too many tiles
      if ((tileList = checkTooManyTiles(layer, wmtSource, layerProperties, renderJob, tileList))
          .isEmpty()) {
        throw new UnsupportedOperationException(Messages.Render_Error_TooManyTiles);
      }

      // Download and display tiles

      // look up the preference for caching tiles on-disk or in
      // memory and use the proper tilerange for that.
      TileRange range = createTileRange(wmtSource, renderJob, tileList);

      // create an empty raster symbolizer for rendering
      RasterSymbolizer style = styleBuilder.createRasterSymbolizer();

      // setup how much each tile is worth for the monitor work %
      int tileCount = range.getTileCount();
      int tileWorth = (tileCount / 100) * tileCount;

      int thisid = 0;
      if (testing) {
        staticid++;
        thisid = staticid;
      }

      // first render any tiles that are ready and render non-ready tiles with blank images
      Map<String, Tile> tiles = range.getTiles();
      Set<String> notRenderedTiles = new HashSet<String>();
      Set<String> renderedTiles = new HashSet<String>();

      renderReadyTiles(
          destination,
          monitor,
          renderJob,
          style,
          tileWorth,
          thisid,
          tiles,
          notRenderedTiles,
          renderedTiles);

      setState(RENDERING);

      // if the tilerange is not already completed, then load
      // the missing tiles
      if (!notRenderedTiles.isEmpty()) {
        renderNotRenderedTiles(
            destination,
            monitor,
            renderJob,
            range,
            style,
            tileWorth,
            thisid,
            notRenderedTiles,
            renderedTiles);
      }

      if (testing) {
        System.out.println("DONE!!!: " + thisid); // $NON-NLS-1$
      }
    } catch (UnsupportedOperationException doneExc) {
      setDone(monitor);

      layer.setStatus(ILayer.ERROR);
      layer.setStatusMessage(doneExc.getMessage());
      WMTPlugin.log("[BasicWMTRenderer.render] Error: ", doneExc); // $NON-NLS-1$

      return;
    } catch (CancellationException cancelExc) {
      return;
    } catch (Exception ex) {
      WMTPlugin.log("[BasicWMTRenderer.render] Unexpected Error: ", ex); // $NON-NLS-1$
    }

    setDone(monitor);
  }
Ejemplo n.º 24
0
  public void doGet(HttpServletRequest request, HttpServletResponse response) {
    log.info("doGet(): " + UsageLog.setupRequestContext(request));
    // System.out.printf("opendap doGet: req=%s%n%s%n", ServletUtil.getRequest(request),
    // ServletUtil.showRequestDetail(this, request));

    String path = null;

    ReqState rs = getRequestState(request, response);

    try {
      path = request.getPathInfo();
      log.debug("doGet path={}", path);

      if (thredds.servlet.Debug.isSet("showRequestDetail"))
        log.debug(ServletUtil.showRequestDetail(this, request));

      if (path == null) {
        log.info(
            "doGet(): "
                + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, -1));
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }

      if (baseURI == null) { // first time, set baseURI
        URI reqURI = ServletUtil.getRequestURI(request);
        // Build base URI from request (rather than hard-coding "/thredds/dodsC/").
        String baseUriString = request.getContextPath() + request.getServletPath() + "/";
        baseURI = reqURI.resolve(baseUriString);
        log.debug("doGet(): baseURI was set = {}", baseURI);
      }

      if (path.endsWith("latest.xml")) {
        DataRootHandler.getInstance().processReqForLatestDataset(this, request, response);
        return;
      }

      // Redirect all catalog requests at the root level.
      if (path.equals("/") || path.equals("/catalog.html") || path.equals("/catalog.xml")) {
        ServletUtil.sendPermanentRedirect(ServletUtil.getContextPath() + path, request, response);
        return;
      }

      // Make sure catalog requests match a dataRoot before trying to handle.
      if (path.endsWith("/") || path.endsWith("/catalog.html") || path.endsWith("/catalog.xml")) {
        if (!DataRootHandler.getInstance().hasDataRootMatch(path)) {
          log.info(
              "doGet(): "
                  + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, -1));
          response.sendError(HttpServletResponse.SC_NOT_FOUND);
          return;
        }

        if (!DataRootHandler.getInstance().processReqForCatalog(request, response))
          log.error(
              "doGet(): "
                  + UsageLog.closingMessageForRequestContext(
                      ServletUtil.STATUS_FORWARD_FAILURE, -1));

        return;
      }

      if (rs != null) {
        String dataSet = rs.getDataSet();
        String requestSuffix = rs.getRequestSuffix();

        if ((dataSet == null) || dataSet.equals("/") || dataSet.equals("")) {
          doGetDIR(rs);
        } else if (requestSuffix.equalsIgnoreCase("blob")) {
          doGetBLOB(rs);
        } else if (requestSuffix.equalsIgnoreCase("close")) {
          doClose(rs);
        } else if (requestSuffix.equalsIgnoreCase("dds")) {
          doGetDDS(rs);
        } else if (requestSuffix.equalsIgnoreCase("das")) {
          doGetDAS(rs);
        } else if (requestSuffix.equalsIgnoreCase("ddx")) {
          doGetDDX(rs);
        } else if (requestSuffix.equalsIgnoreCase("dods")) {
          doGetDAP2Data(rs);
        } else if (requestSuffix.equalsIgnoreCase("asc")
            || requestSuffix.equalsIgnoreCase("ascii")) {
          doGetASC(rs);
        } else if (requestSuffix.equalsIgnoreCase("info")) {
          doGetINFO(rs);
        } else if (requestSuffix.equalsIgnoreCase("html")
            || requestSuffix.equalsIgnoreCase("htm")) {
          doGetHTML(rs);
        } else if (requestSuffix.equalsIgnoreCase("ver")
            || requestSuffix.equalsIgnoreCase("version")
            || dataSet.equalsIgnoreCase("/version")
            || dataSet.equalsIgnoreCase("/version/")) {
          doGetVER(rs);
        } else if (dataSet.equalsIgnoreCase("/help")
            || dataSet.equalsIgnoreCase("/help/")
            || dataSet.equalsIgnoreCase("/" + requestSuffix)
            || requestSuffix.equalsIgnoreCase("help")) {
          doGetHELP(rs);
        } else {
          sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "Unrecognized request");
          return;
        }

      } else {
        sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "Unrecognized request");
        return;
      }

      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, -1));

      // plain ol' 404
    } catch (FileNotFoundException e) {
      sendErrorResponse(response, HttpServletResponse.SC_NOT_FOUND, e.getMessage());

      // DAP2Exception bad url
    } catch (BadURLException e) {
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_BAD_REQUEST, -1));
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      dap2ExceptionHandler(e, rs);

      // all other DAP2Exception
    } catch (DAP2Exception de) {
      int status =
          (de.getErrorCode() == DAP2Exception.NO_SUCH_FILE)
              ? HttpServletResponse.SC_NOT_FOUND
              : HttpServletResponse.SC_BAD_REQUEST;
      if ((de.getErrorCode() != DAP2Exception.NO_SUCH_FILE) && (de.getErrorMessage() != null))
        log.debug(de.getErrorMessage());
      log.info(UsageLog.closingMessageForRequestContext(status, -1));
      response.setStatus(status);
      dap2ExceptionHandler(de, rs);

      // parsing, usually the CE
    } catch (ParseException pe) {
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_BAD_REQUEST, -1));
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      parseExceptionHandler(pe, response);

      // 403 - request too big
    } catch (UnsupportedOperationException e) {
      sendErrorResponse(response, HttpServletResponse.SC_FORBIDDEN, e.getMessage());

    } catch (java.net.SocketException e) {
      log.info("SocketException: " + e.getMessage(), e);
      log.info(UsageLog.closingMessageForRequestContext(ServletUtil.STATUS_CLIENT_ABORT, -1));

    } catch (IOException e) {
      String eName =
          e.getClass().getName(); // dont want compile time dependency on ClientAbortException
      if (eName.equals("org.apache.catalina.connector.ClientAbortException")) {
        log.debug("ClientAbortException: " + e.getMessage());
        log.info(UsageLog.closingMessageForRequestContext(ServletUtil.STATUS_CLIENT_ABORT, -1));
        return;
      }

      log.error("path= " + path, e);
      sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());

      // everything else
    } catch (Throwable t) {
      log.error("path= " + path, t);
      t.printStackTrace();
      sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.getMessage());
    }
  }
Ejemplo n.º 25
0
  /** Run the tool */
  public static void main(String args[]) throws Throwable {
    String inEncoding = args[0];
    String inFile = args[1];
    String outEncoding = args[2];
    String outFile = args[3];
    String outClass = args[4];

    FileInputStream fin = new FileInputStream(inFile);
    InputStreamReader r = new InputStreamReader(fin, inEncoding);
    reader = new BufferedReader(r);

    FileOutputStream fout = new FileOutputStream(outFile);
    OutputStreamWriter w = new OutputStreamWriter(fout, outEncoding);
    writer = new PrintWriter(w);

    // Write the XML file prolog.
    pl("<?xml version=\"1.0\" encoding=\"" + outEncoding + "\"?>");
    pl("<!DOCTYPE configuration SYSTEM \"../configuration.dtd\">");
    pl("<!--");
    pl("         ");
    pl("");
    pl("  Copyright  1990-2009 Sun Microsystems, Inc. All Rights Reserved.");
    pl("  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER");
    pl("  ");
    pl("  This program is free software; you can redistribute it and/or");
    pl("  modify it under the terms of the GNU General Public License version");
    pl("  2 only, as published by the Free Software Foundation.");
    pl("  ");
    pl("  This program is distributed in the hope that it will be useful, but");
    pl("  WITHOUT ANY WARRANTY; without even the implied warranty of");
    pl("  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU");
    pl("  General Public License version 2 for more details (a copy is");
    pl("  included at /legal/license.txt).");
    pl("  ");
    pl("  You should have received a copy of the GNU General Public License");
    pl("  version 2 along with this work; if not, write to the Free Software");
    pl("  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA");
    pl("  02110-1301 USA");
    pl("  ");
    pl("  Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa");
    pl("  Clara, CA 95054 or visit www.sun.com if you need additional");
    pl("  information or have any questions.");
    pl("-->");
    pl("<configuration>");
    pl("<localized_strings Package=\"com.sun.midp.l10n\" Name=\"" + outClass + "\">");

    StringBuffer sbuf = new StringBuffer();
    String line;
    while ((line = reader.readLine()) != null) {
      sbuf.append(line);
      sbuf.append("\n");
    }

    // Find all occurrences of
    // new Integer(ResourceConstants.DONE), "\u5B8C\u6210"
    //                               ^^^^    ^^^^^^^^^^^^
    //                               key     value
    Parser p = new Parser(sbuf.toString());
    while (p.advance("Integer")) {
      p.mark();
      try {
        p.skipSpaces();
        p.skip('(');
        p.skipSpaces();
        p.skip("ResourceConstants");
        p.skipSpaces();
        p.skip(".");
        p.skipSpaces();

        String key = p.readSymbol();

        p.skipSpaces();
        p.skip(')');
        p.skipSpaces();
        p.skip(',');
        p.skipSpaces();

        String value = p.readStringLiteral();

        while (true) {
          p.mark();

          try {
            // Handle any "xxx" + "yyy" cases
            p.skipSpaces();
            p.skip('+');
            p.skipSpaces();
            String more = p.readStringLiteral();
            value += more;
            p.pop();
          } catch (Error t) {
            p.reset();
            break;
          }
        }
        pl("<localized_string Key=\"" + key + "\"");
        pl("                Value=\"" + quote(value) + "\"/>");
      } catch (UnsupportedOperationException t) {
        System.out.println("Error: " + t.getMessage());
        System.out.println("at line " + p.countLine());
        System.out.println("at character " + p.countPos());
        System.exit(1);
      } catch (Error t) {
        // This loop will eventually terminate, since we at least
        // consume ".*Integer" from each iteration.
        p.reset();
      }
    }
    pl("</localized_strings>");
    pl("</configuration>");
    writer.close();
  }