Пример #1
0
  @Override
  public void uploadStarted(final ClientFile clientFile, final InputStream in) throws Exception {
    assert handler != null : "No handler set for Upload.";

    // give the thread the proper session context (but outside UI thread)
    sessionContext.execute(
        new Callable() {
          public Object call() throws Exception {
            handler.uploadStarted(
                clientFile,
                new ProgressInputStream(in, clientFile.getName(), clientFile.getSize()));
            return null;
          }
        });
  }
    @Override
    public void sendContent(
        OutputStream out, Range range, Map<String, String> params, String contentType)
        throws IOException, BadRequestException {
      WorkbenchState state = WorkbenchState.instance(SessionContext.current());
      IMap map = state.getMap();

      try {
        JSONObject json = new JSONObject();
        json.put("width", -1);
        json.put("height", -1);

        ReferencedEnvelope extent = map.getExtent();
        json.put("minX", extent.getMinX());
        json.put("minY", extent.getMinY());
        json.put("maxX", extent.getMaxX());
        json.put("maxY", extent.getMaxY());

        out.write(json.toString(4).getBytes("UTF-8"));
      } catch (JSONException e) {
        throw new RuntimeException(e);
      }
    }
    @Override
    public void sendContent(
        OutputStream out, Range range, Map<String, String> params, String contentType)
        throws IOException, BadRequestException {
      WorkbenchState state = WorkbenchState.instance(SessionContext.current());
      try {
        FeatureCollection features = state.getSelectedFeatures();
        if (features != null) {
          FeatureJSON encoder = new FeatureJSON();
          encoder.setEncodeFeatureBounds(false);
          encoder.setEncodeFeatureCollectionBounds(false);
          encoder.setEncodeFeatureCollectionCRS(false);
          encoder.setEncodeFeatureCRS(false);

          encoder.writeFeatureCollection(features, out);
        } else {
          out.write("{\"type\": \"FeatureCollection\",\"features\": []}".getBytes("UTF-8"));
        }
      } catch (Exception e) {
        log.debug("", e);
        throw new RuntimeException(e);
      }
    }
    @Override
    public void sendContent(
        OutputStream out, Range range, final Map<String, String> params, String rContentType)
        throws IOException, BadRequestException {
      final int width = params.containsKey("width") ? Integer.parseInt(params.get("width")) : 300;
      final int height =
          params.containsKey("height") ? Integer.parseInt(params.get("height")) : 300;

      List<Job> jobs = new ArrayList();
      final Map<ILayer, Image> images = new HashMap();

      // run jobs for all layers
      WorkbenchState state = WorkbenchState.instance(SessionContext.current());
      final IMap map = state.getMap();
      if (map != null) {
        for (final ILayer layer : map.getLayers()) {
          if (layer.isVisible()) {
            UIJob job =
                new UIJob(getClass().getSimpleName() + ": " + layer.getLabel()) {
                  protected void runWithException(IProgressMonitor monitor) throws Exception {
                    try {
                      IGeoResource res = layer.getGeoResource();
                      if (res == null) {
                        throw new RuntimeException(
                            "Unable to find geo resource of layer: " + layer);
                      }
                      IService service = res.service(null);
                      Pipeline pipeline =
                          pipelineIncubator.newPipeline(
                              LayerUseCase.IMAGE, layer.getMap(), layer, service);
                      if (pipeline.length() == 0) {
                        throw new RuntimeException(
                            "Unable to build processor pipeline for layer: " + layer);
                      }

                      // processor request
                      GetMapRequest request =
                          new GetMapRequest(
                              null, // layers
                              map.getCRSCode(),
                              map.getExtent(),
                              contentType,
                              width,
                              height,
                              -1);

                      // process request
                      pipeline.process(
                          request,
                          new ResponseHandler() {
                            public void handle(ProcessorResponse pipeResponse) throws Exception {
                              Image image = ((ImageResponse) pipeResponse).getImage();
                              images.put(layer, image);
                            }
                          });
                    } catch (Exception e) {
                      // XXX put a special image in the map
                      log.warn("", e);
                      images.put(layer, null);
                      throw e;
                    }
                  }
                };
            jobs.add(job);
            job.schedule();
          }
        }

        // join jobs
        for (Job job : jobs) {
          try {
            job.join();
          } catch (InterruptedException e) {
            // XXX put a special image in the map
            log.warn("", e);
          }
        }
      }

      // put images together (MapContext order)
      Graphics2D g = null;
      try {
        // create image
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        g = result.createGraphics();

        // rendering hints
        RenderingHints hints =
            new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        hints.add(
            new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
        hints.add(
            new RenderingHints(
                RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
        g.setRenderingHints(hints);

        if (map == null) {
          g.setFont(new Font("Serif", Font.PLAIN, 14));
          g.setColor(Color.RED);
          g.drawString("Melden Sie sich in der Workbench an, um hier eine Karte zu sehen!", 50, 50);
        }
        // FIXME honor layer.getOrderKey()
        for (Map.Entry<ILayer, Image> entry : images.entrySet()) {
          int rule = AlphaComposite.SRC_OVER;
          float alpha = ((float) entry.getKey().getOpacity()) / 100;

          g.setComposite(AlphaComposite.getInstance(rule, alpha));
          g.drawImage(entry.getValue(), 0, 0, null);
        }

        // encode image
        encodeImage(result, out);
      } finally {
        if (g != null) {
          g.dispose();
        }
      }
    }
 @Override
 public Date getModifiedDate() {
   WorkbenchState state = WorkbenchState.instance(SessionContext.current());
   return state.getMapModified();
 }
Пример #6
0
/** @author <a href="http://www.polymap.de">Falko Bräutigam</a> */
public class Upload extends Composite implements IUploadHandler {

  private static Log log = LogFactory.getLog(Upload.class);

  public static final int SHOW_UPLOAD_BUTTON = 1;
  public static final int SHOW_PROGRESS = 2;

  private static final IMessages i18n = Messages.forPrefix("Upload");

  private FileUpload fileUpload;

  private ProgressBar progress;

  private Label progressLabel;

  private IUploadHandler handler;

  private SessionContext sessionContext = SessionContext.current();

  private Display display = getDisplay();

  public Upload(Composite parent, int style, int... uploadStyles) {
    super(parent, style);
    setLayout(FormLayoutFactory.defaults().create());

    fileUpload = new FileUpload(this, SWT.NONE);
    fileUpload.setLayoutData(FormDataFactory.filled().create());
    fileUpload.setText(i18n.get("select"));
    fileUpload.setData(RWT.TOOLTIP_MARKUP_ENABLED, Boolean.TRUE);
    setData(RWT.TOOLTIP_MARKUP_ENABLED, Boolean.TRUE);

    fileUpload.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent ev) {
            UIUtils.activateCallback("upload");
            fileUpload.submit(UploadService.registerHandler(Upload.this));
          }
        });

    if (ArrayUtils.contains(uploadStyles, SHOW_UPLOAD_BUTTON)) {
      log.info("SHOW_UPLOAD_BUTTON is not supported yet.");
    }

    if (ArrayUtils.contains(uploadStyles, SHOW_PROGRESS)) {
      fileUpload.setLayoutData(FormDataFactory.filled().noRight().create());

      progress = new ProgressBar(this, SWT.HORIZONTAL);
      progress.setLayoutData(FormDataFactory.filled().left(fileUpload).create());
      progress.setMaximum(Integer.MAX_VALUE);

      progressLabel = new Label(this, SWT.NONE);
      progressLabel.setLayoutData(FormDataFactory.filled().top(0, 5).left(fileUpload, 20).create());
      progressLabel.setText(i18n.get("progressLabel"));
      log.warn("not yet ported: progressLabel.setForeground( new Color( 0x60, 0x60, 0x60 ) ) ");
      progressLabel.moveAbove(progress);
    }
  }

  @Override
  public void dispose() {
    super.dispose();
    UploadService.removeHandler(Upload.this);
    UIUtils.deactivateCallback("upload");
  }

  public IUploadHandler getHandler() {
    return handler;
  }

  public Upload setText(String text) {
    fileUpload.setText(text);
    return this;
  }

  public Upload setImage(Image image) {
    fileUpload.setImage(image);
    return this;
  }

  public Upload setHandler(IUploadHandler handler) {
    this.handler = handler;
    return this;
  }

  @Override
  public void uploadStarted(final ClientFile clientFile, final InputStream in) throws Exception {
    assert handler != null : "No handler set for Upload.";

    // give the thread the proper session context (but outside UI thread)
    sessionContext.execute(
        new Callable() {
          public Object call() throws Exception {
            handler.uploadStarted(
                clientFile,
                new ProgressInputStream(in, clientFile.getName(), clientFile.getSize()));
            return null;
          }
        });
  }

  /** */
  class ProgressInputStream extends FilterInputStream {

    private String name;

    private long count = 0;

    private long contentLength;

    private ProgressInputStream(InputStream in, String name, long contentLength) {
      super(in);
      this.name = name;
      this.contentLength = contentLength > 0 ? contentLength : 10 * 1024 * 1024;
    }

    @Override
    public int read() throws IOException {
      throw new RuntimeException("not implemented.");
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
      final int result = super.read(b, off, len);

      //            try { Thread.sleep( 1000 ); } catch (InterruptedException e) {}

      if (progress != null && !progress.isDisposed()) {
        display.asyncExec(
            new Runnable() {
              public void run() {
                count += result;
                // init maximum (inside UI thread)
                if (progress.getMaximum() == Integer.MAX_VALUE) {
                  progress.setMaximum((int) contentLength);
                }
                if (result == -1) {
                  progress.setSelection(progress.getMaximum());
                  UIUtils.deactivateCallback("upload");
                } else {
                  progress.setSelection((int) count);
                }
                // adjust contentLength
                if (count >= contentLength) {
                  contentLength = count * 2;
                  progress.setMaximum((int) contentLength);
                }
                // int percent = 100 * progress.getSelection() / progress.getMaximum();
                progressLabel.setText(
                    name
                        + " ("
                        + FileUtils.byteCountToDisplaySize(count)
                        /*+ " - " + percent + "%"*/ + ")");
              }
            });
      }
      return result;
    }
  }
}