コード例 #1
0
    private void addFileUploadWidget() {
      final FileUpload upload = new FileUpload();
      upload.setWidth("200px");
      upload.setName(getUniqueId());
      uploadForms.add(upload);
      final HorizontalPanel hPanel = new HorizontalPanel();
      hPanel.setHeight("30px");
      hPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
      // Don't display ability to remove form if expecting exactly 1 upload or if this is the first
      // upload element
      if (isMultiple() && uploadForms.size() > 1) {
        com.google.gwt.user.client.ui.Image crossImage = new com.google.gwt.user.client.ui.Image();
        crossImage.setUrl(Resources.CROSS);
        crossImage.addClickHandler(
            new com.google.gwt.event.dom.client.ClickHandler() {
              public void onClick(final com.google.gwt.event.dom.client.ClickEvent clickEvent) {
                panel.remove(hPanel);
                uploadForms.remove(hPanel.getWidget(1));
              }
            });
        hPanel.add(crossImage);
      } else {
        com.google.gwt.user.client.ui.VerticalPanel space =
            new com.google.gwt.user.client.ui.VerticalPanel();
        space.setSize("16px", "1px");
        hPanel.add(space);
      }

      hPanel.add(upload);
      panel.add(hPanel);
      if (get() != null) {
        get().markForRedraw();
      }
    }
コード例 #2
0
  public void testFileUpload() {
    System.out.println("testFileUpload");
    final FormPanel form = new FormPanel();
    form.setMethod(FormPanel.METHOD_POST);
    form.setEncoding(FormPanel.ENCODING_MULTIPART);
    assertEquals(FormPanel.ENCODING_MULTIPART, form.getEncoding());
    form.setAction(GWT.getModuleBaseURL() + "formHandler");

    FileUpload file = new FileUpload();
    file.setName("file0");
    form.setWidget(file);

    RootPanel.get().add(form);

    delayTestFinish(TEST_DELAY);
    form.addSubmitCompleteHandler(
        new SubmitCompleteHandler() {
          public void onSubmitComplete(SubmitCompleteEvent event) {
            // The server just echoes the contents of the request. The following
            // string should have been present in it.
            assertTrue(
                event.getResults().indexOf("Content-Disposition: form-data; name=\"file0\";")
                    != -1);
            finishTest();
          }
        });
    form.submit();
  }
コード例 #3
0
 public List<String> getNames() {
   if (!hasNames()) {
     return null;
   }
   final List<String> names = Lists.newArrayList();
   for (final FileUpload upload : uploadForms) {
     names.add(upload.getFilename());
   }
   return names;
 }
コード例 #4
0
  /**
   * Creates a FileUpload widget that wraps an existing &lt;input type='file'&gt; element.
   *
   * <p>This element must already be attached to the document. If the element is removed from the
   * document, you must call {@link RootPanel#detachNow(Widget)}.
   *
   * @param element the element to be wrapped
   */
  public static FileUpload wrap(Element element) {
    // Assert that the element is attached.
    assert Document.get().getBody().isOrHasChild(element);

    FileUpload fileUpload = new FileUpload(element);

    // Mark it attached and remember it for cleanup.
    fileUpload.onAttach();
    RootPanel.detachOnWindowClose(fileUpload);

    return fileUpload;
  }
コード例 #5
0
 private void addFile() {
   file = new FileUpload();
   file.setHeight("22px");
   file.setWidth("100%");
   file.setName("file");
   file.ensureDebugId("file-uploadFile-ChooseFile");
   file.addChangeHandler(
       new ChangeHandler() {
         @Override
         public void onChange(ChangeEvent event) {
           delegate.onFileNameChanged();
         }
       });
   uploadPanel.insert(file, 0);
 }
コード例 #6
0
 @Override
 public Widget createViewOnlyLabel() {
   clearDisplayPanel();
   displayPanel.add(descriptionLabel);
   displayPanel.add(new HTML("Uploaded:" + fileUpload.getFilename()));
   return displayPanel;
 }
コード例 #7
0
ファイル: GSTCloud.java プロジェクト: jomolinare/gstcloud
 /** This is the entry point method. */
 private void setupFileUpload() {
   upload.setName("KmlFileUpload");
   uiObject.fpAdmin.setWidget(uiObject.vpAdmin1);
   uiObject.fpAdmin.setAction(GWT.getModuleBaseURL() + "FileUp");
   uiObject.fpAdmin.setEncoding(FormPanel.ENCODING_MULTIPART);
   uiObject.fpAdmin.setMethod(FormPanel.METHOD_POST);
   uiObject.hpAdmin.add(upload);
 }
コード例 #8
0
 /** {@inheritDoc} */
 @Override
 @Nonnull
 public String getFileName() {
   String fileName = file.getFilename();
   if (fileName.contains("/") || fileName.contains("\\")) {
     int index =
         fileName.contains("\\") ? fileName.lastIndexOf("\\") + 1 : fileName.lastIndexOf("/") + 1;
     fileName = fileName.substring(index);
   }
   return fileName;
 }
コード例 #9
0
 public CanUpload canUpload() {
   for (FileUpload upload : uploadForms) {
     final String filename = upload.getFilename();
     if (filename == null || filename.trim().length() == 0) {
       return CanUpload.cannotUpload("File not specified.");
     }
     if (types != null) {
       if (!filename.matches(types.replace(";", "|").replace("*", ".*"))) {
         return CanUpload.cannotUpload(
             "Selected file "
                 + filename
                 + " doesn't appear to be a valid "
                 + typesDescription
                 + "("
                 + types
                 + ") file.");
       }
     }
   }
   return CanUpload.canUpload();
 }
コード例 #10
0
ファイル: ImportManager.java プロジェクト: INBio/m3s
  /** Inits the fileUpload Widget and the help text besaides the uploadForm */
  private void initFileUploadPanel() {
    this.setSpacing(10);

    // upload widget
    uploadForm = new FormPanel();
    uploadForm.setAction(GWT.getModuleBaseURL() + "uploadImportFile");

    uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
    uploadForm.setMethod(FormPanel.METHOD_POST);

    upload = new VerticalPanel();
    upload.setSpacing(10);
    uploadForm.setWidget(upload);

    // Create a FileUpload widget.
    uploadWidget = new FileUpload();
    uploadWidget.setName("uploadFormElement");
    upload.add(uploadWidget);
    fileUploadPanel.add(uploadForm);

    // Add a 'upload' button.
    uploadButton =
        new Button(
            "subir",
            new ClickListener() {
              public void onClick(Widget sender) {
                if (LoginManager.isUserLogged()) {
                  usernameImportOwner = LoginManager.getUserName();
                  uploadForm.submit();
                } else {
                  Window.alert("Debe iniciar sesion en el sistema.");
                }
              }
            });
    upload.add(uploadButton);

    // uploadForm.addFormHandler(this);
    uploadForm.addFormHandler(this);

    // uploadhelp label
    uploadHelp =
        new Label(
            "Busque el archivo de importación y de click en 'subir', "
                + "seguidamente el archivo se cargara en el serrvidor y la "
                + "importación comenzará una vez el archivo se haya subido "
                + "correctamente");
    fileUploadPanel.add(uploadHelp);
  }
コード例 #11
0
  public AttachmentsEditorView() {
    initWidget(uiBinder.createAndBindUi(this));

    attachmentForm.setEncoding(FormPanel.ENCODING_MULTIPART);
    attachmentForm.setMethod(FormPanel.METHOD_POST);
    attachment.setName("attachment0");
    attachmentDescription.setName("description0");
    hiddenTaskHandle.setName(AttachmentUploadUtil.TASK_HANDLE_FORM_NAME);

    attachmentSubmitButton.addClickHandler(
        new ClickHandler() {

          @Override
          public void onClick(ClickEvent event) {
            attachmentForm.submit();
          }
        });
  }
コード例 #12
0
 @Override
 public boolean onBrowserEvent(Event event) {
   switch (event.getTypeInt()) {
     case Event.ONCHANGE:
       // When we fire the change event onBlur, we allow it to pass to
       // Widget#onBrowserEvent().
       if (!allowEvent) {
         eventPending = true;
         return false;
       }
       break;
     case Event.ONBLUR:
       // Trigger a change event now.
       if (eventPending) {
         allowEvent = true;
         fileUpload.getElement().dispatchEvent(Document.get().createChangeEvent());
         allowEvent = false;
         eventPending = false;
       }
       break;
   }
   return true;
 }
コード例 #13
0
 @UiHandler("uploadModuleBrowseButton")
 void clickUploadModuleBrowseButton(ClickEvent event) {
   uploadModuleFileUpload.getElement().<InputElement>cast().click();
 }
コード例 #14
0
 @UiHandler(value = {"uploadFile"})
 void showFileBrowser(ChangeEvent event) {
   uploadFilePath.setText(uploadFile.getFilename());
 }
コード例 #15
0
 @UiHandler("uploadFormPanel")
 void reset(FormPanel.SubmitCompleteEvent e) {
   uploadFile.getElement().setPropertyString("value", "");
   uploadFilePath.setText(MSG_CHOOSE_FILE);
 }
コード例 #16
0
ファイル: UIEditMenuItem.java プロジェクト: pgilmon/Comanda
  private boolean validate() {
    boolean result = true;
    String description = taDescription.getText();
    String name = tbName.getText();
    String imageFile = fuImageFile.getFilename();
    if (rbSinglePrice.getValue()) {
      fixPriceFormat(dbSinglePrice);
      if (dbSinglePrice.getValue() == null) {
        Window.alert("El precio introducido no es válido");
        result = false;
      }
    } else {
      boolean oneChecked = false;
      if (cbSmall.getValue()) {
        oneChecked = true;
        fixPriceFormat(dbSmallPrice);
        if (dbSmallPrice.getValue() == null) {
          Window.alert("El precio introducido para 'Pequeña' no es válido");
          result = false;
        }
      }
      if (result && cbMedium.getValue()) {
        oneChecked = true;
        fixPriceFormat(dbMediumPrice);
        if (dbMediumPrice.getValue() == null) {
          Window.alert("El precio introducido para 'Mediana' no es válido");
          result = false;
        }
      }
      if (result && cbLarge.getValue()) {
        oneChecked = true;
        fixPriceFormat(dbLargePrice);
        if (dbLargePrice.getValue() == null) {
          Window.alert("El precio introducido para 'Grande' no es válido");
          result = false;
        }
      }
      if (result && cbTapa.getValue()) {
        oneChecked = true;
        fixPriceFormat(dbTapaPrice);
        if (dbTapaPrice.getValue() == null) {
          Window.alert("El precio introducido para 'Tapa' no es válido");
          result = false;
        }
      }
      if (result && cbHalf.getValue()) {
        oneChecked = true;
        fixPriceFormat(dbHalfPrice);
        if (dbHalfPrice.getValue() == null) {
          Window.alert("El precio introducido para '1/2 Ración' no es válido");
          result = false;
        }
      }
      if (result && cbFull.getValue()) {
        oneChecked = true;
        fixPriceFormat(dbFullPrice);
        if (dbFullPrice.getValue() == null) {
          Window.alert("El precio introducido para 'Ración' no es válido");
          result = false;
        }
      }
    }

    if (result) {
      if (name == null || name.length() == 0) {
        Window.alert("Por favor, introduzca el nombre");
        result = false;
      }
    }
    return result;
  }
コード例 #17
0
ファイル: NewPackageWizard.java プロジェクト: pappist/guvnor
  private Widget newImportWidget(final FormStylePopup parent) {

    final FormPanel uploadFormPanel = new FormPanel();
    uploadFormPanel.setAction(GWT.getModuleBaseURL() + "package");
    uploadFormPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
    uploadFormPanel.setMethod(FormPanel.METHOD_POST);

    VerticalPanel panel = new VerticalPanel();
    uploadFormPanel.setWidget(panel);

    final FileUpload upload = new FileUpload();
    upload.setName(HTMLFileManagerFields.CLASSIC_DRL_IMPORT);
    panel.add(upload);

    HorizontalPanel hp = new HorizontalPanel();
    Button create = new Button(constants.Import());
    ClickHandler okClickHandler =
        new ClickHandler() {
          public void onClick(ClickEvent arg0) {
            if (Window.confirm(constants.ImportMergeWarning())) {
              uploadFormPanel.submit();
            }
          }
        };
    create.addClickHandler(okClickHandler);
    hp.add(create);

    Button cancel = new Button(constants.Cancel());
    cancel.addClickHandler(
        new ClickHandler() {
          public void onClick(ClickEvent arg0) {
            parent.hide();
          }
        });
    hp.add(cancel);
    panel.add(hp);

    final FormStylePopup packageNamePopup =
        new FormStylePopup(images.packageLarge(), constants.PackageName());
    HorizontalPanel packageNamePanel = new HorizontalPanel();
    packageNamePopup.addRow(new Label(constants.ImportedDRLContainsNoNameForThePackage()));

    final TextBox packageName = new TextBox();
    packageNamePanel.add(new Label(constants.PackageName() + ":"));
    packageNamePanel.add(packageName);
    Button uploadWithNameButton = new Button(constants.OK());
    uploadWithNameButton.addClickHandler(okClickHandler);

    packageNamePanel.add(uploadWithNameButton);
    packageNamePopup.addRow(packageNamePanel);
    uploadFormPanel.addSubmitCompleteHandler(
        new SubmitCompleteHandler() {
          public void onSubmitComplete(SubmitCompleteEvent event) {
            if (event.getResults().indexOf("OK") > -1) { // NON-NLS
              LoadingPopup.close();
              Window.alert(constants.PackageWasImportedSuccessfully());

              eventBus.fireEvent(new RefreshModuleListEvent());
              parent.hide();
              if (packageNamePopup != null) {
                packageNamePopup.hide();
              }
            } else if (event.getResults().indexOf("Missing package name.") > -1) {
              LoadingPopup.close();
              packageNamePopup.show();
            } else {
              ErrorPopup.showMessage(constants.UnableToImportIntoThePackage0(event.getResults()));
            }
            LoadingPopup.close();
          }
        });

    uploadFormPanel.addSubmitHandler(
        new SubmitHandler() {
          public void onSubmit(SubmitEvent event) {
            if (upload.getFilename().length() == 0) {
              LoadingPopup.close();
              Window.alert(constants.YouDidNotChooseADrlFileToImport());
              event.cancel();
            } else if (!upload.getFilename().endsWith(".drl")) { // NON-NLS
              LoadingPopup.close();
              Window.alert(constants.YouCanOnlyImportDrlFiles());
              event.cancel();
            } else if (packageName.getText() != null && !packageName.getText().equals("")) {
              LoadingPopup.showMessage(constants.ImportingDRLPleaseWait());
              uploadFormPanel.setAction(
                  uploadFormPanel.getAction() + "?packageName=" + packageName.getText());
            } else {
              LoadingPopup.showMessage(constants.CreatingPackagePleaseWait());
            }
          }
        });

    return uploadFormPanel;
  }
コード例 #18
0
  /**
   * Create an avatar upload form element.
   *
   * @param label the label of the element.
   * @param desc the description.
   * @param servletPath the path to hit to upload the image
   * @param inProcessor the processor.
   * @param inStrategy the strategy.
   */
  public AvatarUploadFormElement(
      final String label,
      final String desc,
      final String servletPath,
      final ActionProcessor inProcessor,
      final ImageUploadStrategy inStrategy) {
    description = desc;
    strategy = inStrategy;
    Boolean resizeable = strategy.isResizable();

    errorBox = new FlowPanel();
    errorBox.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formErrorBox());
    errorBox.add(
        new Label(
            "There was an error uploading your image. Please be sure "
                + "that your photo is under 4MB and is a PNG, JPG, or GIF."));

    errorBox.setVisible(false);

    this.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formAvatarUpload());
    this.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formElement());

    processor = inProcessor;
    // AvatarEntity Entity = inEntity;

    uploadForm.setAction(servletPath);

    uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
    uploadForm.setMethod(FormPanel.METHOD_POST);

    Label photoLabel = new Label(label);
    photoLabel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formLabel());
    panel.add(photoLabel);

    FlowPanel avatarModificationPanel = new FlowPanel();
    avatarModificationPanel.addStyleName(
        StaticResourceBundle.INSTANCE.coreCss().avatarModificationPanel());

    avatarContainer.addStyleName(StaticResourceBundle.INSTANCE.coreCss().avatarContainer());
    avatarModificationPanel.add(avatarContainer);

    FlowPanel photoButtonPanel = new FlowPanel();
    photoButtonPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formPhotoButtonPanel());

    if (resizeable) {
      editButton = new Anchor("Resize");
      editButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formResizeButton());
      editButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formButton());
      photoButtonPanel.add(editButton);
    }

    deleteButton = new Anchor("Delete");
    deleteButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formDeleteButton());
    deleteButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formButton());
    photoButtonPanel.add(deleteButton);

    avatarModificationPanel.add(photoButtonPanel);
    panel.add(avatarModificationPanel);

    FlowPanel uploadPanel = new FlowPanel();
    uploadPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formUploadPanel());
    uploadPanel.add(errorBox);

    // Wrapping the FileUpload because otherwise IE7 shifts it way
    // to the right. I couldn't figure out why,
    // but for whatever reason, this works.
    FlowPanel fileUploadWrapper = new FlowPanel();
    FileUpload upload = new FileUpload();
    upload.setName("imageUploadFormElement");
    upload.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formAvatarUpload());
    fileUploadWrapper.add(upload);
    uploadPanel.add(fileUploadWrapper);

    uploadPanel.add(new Label(description));
    Anchor submitButton = new Anchor("");
    submitButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formUploadButton());
    submitButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formButton());

    uploadPanel.add(submitButton);

    hiddenImage = new Image();
    hiddenImage.addStyleName(StaticResourceBundle.INSTANCE.coreCss().avatarHiddenOriginal());
    uploadPanel.add(hiddenImage);

    panel.add(uploadPanel);

    submitButton.addClickHandler(
        new ClickHandler() {
          public void onClick(final ClickEvent event) {
            uploadForm.submit();
          }
        });

    uploadForm.setWidget(panel);
    this.add(uploadForm);

    uploadForm.addSubmitCompleteHandler(
        new SubmitCompleteHandler() {
          public void onSubmitComplete(final SubmitCompleteEvent ev) {
            String result = ev.getResults().replaceAll("\\<.*?\\>", "");
            final boolean fail = "fail".equals(result);
            errorBox.setVisible(fail);
            if (!fail) {
              String[] results = result.split(",");
              if (results.length >= 4) {
                strategy.setX(Integer.parseInt(results[1]));
                strategy.setY(Integer.parseInt(results[2]));
                strategy.setCropSize(Integer.parseInt(results[3]));
              }
              onAvatarIdChanged(results[0], strategy.getEntityType() == EntityType.PERSON);
            }
          }
        });

    if (editButton != null) {
      editButton.addClickHandler(
          new ClickHandler() {
            public void onClick(final ClickEvent inArg0) {
              // Since the size of the image is required before we can correctly show the
              // resize dialog, this method determines the avatar url and sets image url.
              // The load event of that image being loaded will kick off the resize modal.
              AvatarUrlGenerator urlGenerator = new AvatarUrlGenerator(EntityType.PERSON);
              hiddenImage.setUrl(urlGenerator.getOriginalAvatarUrl(avatarId));
            }
          });
      hiddenImage.addLoadHandler(
          new LoadHandler() {
            public void onLoad(final LoadEvent inEvent) {
              imageCropDialog =
                  new ImageCropContent(
                      strategy,
                      processor,
                      avatarId,
                      new Command() {
                        public void execute() {
                          onAvatarIdChanged(
                              strategy.getImageId(), strategy.getEntityType() == EntityType.PERSON);
                        }
                      },
                      hiddenImage.getWidth() + "px",
                      hiddenImage.getHeight() + "px");

              Dialog dialog = new Dialog(imageCropDialog);
              dialog.showCentered();
            }
          });
    }

    if (strategy.getImageType().equals(ImageType.BANNER)) {
      onAvatarIdChanged(
          strategy.getImageId(),
          strategy.getId().equals(strategy.getImageEntityId()),
          true,
          strategy.getEntityType() == EntityType.PERSON);
    } else {
      onAvatarIdChanged(strategy.getImageId(), strategy.getEntityType() == EntityType.PERSON);
    }

    deleteButton.addClickHandler(
        new ClickHandler() {
          @SuppressWarnings("unchecked")
          public void onClick(final ClickEvent event) {
            if (new WidgetJSNIFacadeImpl()
                .confirm("Are you sure you want to delete your current photo?")) {
              strategy.getDeleteAction().delete(strategy.getDeleteParam());
            }
          }
        });

    Session.getInstance()
        .getEventBus()
        .addObserver(
            ClearUploadedImageEvent.class,
            new Observer<ClearUploadedImageEvent>() {
              public void update(final ClearUploadedImageEvent event) {
                if (event.getImageType().equals(strategy.getImageType())
                    && event.getEntityType().equals(strategy.getEntityType())) {
                  if (event.getImageType().equals(ImageType.BANNER)) {
                    onAvatarIdChanged(
                        event.getEntity().getBannerId(),
                        strategy.getId().equals(event.getEntity().getBannerEntityId()),
                        true,
                        strategy.getEntityType() == EntityType.PERSON);
                  } else {
                    onAvatarIdChanged(null, strategy.getEntityType() == EntityType.PERSON);
                  }
                }
              }
            });
  }
コード例 #19
0
 @Override
 public void init(FileUpload fileUpload) {
   this.fileUpload = fileUpload;
   fileUpload.sinkEvents(Event.ONBLUR);
 }
コード例 #20
0
  private void createUploadComponent(String uploadAction, final GPExtensions... extensions) {
    uploaderProgressBar = new UploaderProgressBar();
    formPanel.setAction(GWT.getModuleBaseURL() + uploadAction);
    formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
    formPanel.setMethod(FormPanel.METHOD_POST);

    this.verticalPanel = new VerticalPanel();

    this.queryParameter = new Hidden();

    this.verticalPanel.add(queryParameter);

    formPanel.setWidget(verticalPanel);

    fileUpload = new FileUpload();
    fileUpload.setName("uploadFormElement");
    verticalPanel.add(fileUpload);

    buttonSubmit =
        new Button(
            ButtonsConstants.INSTANCE.submitText(),
            new SelectionListener<ButtonEvent>() {

              @Override
              public void componentSelected(ButtonEvent ce) {
                uploaderProgressBar.show("Uploading...");
                formPanel.submit();
                if ((fileUpload.getFilename() != null)
                    && isValidExtensions(fileUpload.getFilename(), extensions)) {
                  LayoutManager.getInstance()
                      .getStatusMap()
                      .setBusy(BasicWidgetConstants.INSTANCE.GPFileUploader_uploadInProgressText());
                }
              }
            });
    verticalPanel.add(buttonSubmit);

    // Add an event handler to the form.
    formPanel.addSubmitHandler(
        new FormPanel.SubmitHandler() {

          @Override
          public void onSubmit(SubmitEvent event) {
            // This event is fired just before the form is submitted. We can
            // take this opportunity to perform validation
            if (!isValidExtensions(fileUpload.getFilename(), extensions)) {
              uploaderProgressBar.hide();
              LayoutManager.getInstance()
                  .getStatusMap()
                  .setStatus(
                      BasicWidgetConstants.INSTANCE.GPFileUploader_failedStatusText(),
                      EnumSearchStatus.STATUS_NO_SEARCH.toString());
              GeoPlatformMessage.errorMessage(
                  BasicWidgetConstants.INSTANCE.GPFileUploader_failedErrorMessageTitleText(),
                  BasicWidgetConstants.INSTANCE.GPFileUploader_failedErrorKindFileBodyText());
              event.cancel();
              formPanel.reset();
            }
          }
        });

    formPanel.addSubmitCompleteHandler(
        new FormPanel.SubmitCompleteHandler() {

          @Override
          public void onSubmitComplete(SubmitCompleteEvent event) {
            // When the form submission is successfully completed,
            // this event is fired. Assuming the service returned a
            // response of type text/html, we can get the result text here
            // (see the FormPanel documentation for further explanation)
            htmlResult = event.getResults();
            System.out.println("HTML Result: " + htmlResult);
            // Execute this code only if the session is still alive
            if (htmlResult.contains("Session Timeout")) {
              GPHandlerManager.fireEvent(new GPLoginEvent(null));
            } else if (!htmlResult.contains("HTTP ERROR")) {
              formPanel.reset();
              htmlResult = htmlResult.replaceAll("<pre>", "");
              htmlResult = htmlResult.replaceAll("</pre>", "");
              htmlResult =
                  htmlResult.replaceAll(
                      "<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">", "");
              if (GPSharedUtils.isNotEmpty(htmlResult)) {
                //                                logger.info("HTMLResult: " + htmlResult);
                uploadEvent.setResult(htmlResult);
                GPHandlerManager.fireEvent(uploadEvent);
                // done.enable();
                // mapPreviewWidget.drawAoiOnMap(wkt);
                LayoutManager.getInstance()
                    .getStatusMap()
                    .setStatus(
                        BasicWidgetConstants.INSTANCE.GPFileUploader_successStatusText(),
                        EnumSearchStatus.STATUS_SEARCH.toString());
              } else {
                LayoutManager.getInstance()
                    .getStatusMap()
                    .setStatus(
                        BasicWidgetConstants.INSTANCE.GPFileUploader_failedStatusText(),
                        EnumSearchStatus.STATUS_NO_SEARCH.toString());
              }
            } else {
              GeoPlatformMessage.errorMessage(
                  BasicWidgetConstants.INSTANCE.GPFileUploader_failedErrorMessageTitleText(),
                  BasicWidgetConstants.INSTANCE.GPFileUploader_failedErrorGenericBodyText());
              LayoutManager.getInstance()
                  .getStatusMap()
                  .setStatus(
                      BasicWidgetConstants.INSTANCE.GPFileUploader_failedStatusText(),
                      EnumSearchStatus.STATUS_NO_SEARCH.toString());
            }
            uploaderProgressBar.hide();
          }
        });
  }
コード例 #21
0
ファイル: UploadTab.java プロジェクト: policygrid/LIBER
  /**
   * Constructor. Displays the upload pane, with an upload widget and a next button.
   *
   * @param wys Entrypoint
   */
  public UploadTab(WYSIWYMinterface wys) {
    super();
    parent = wys;
    setStyleName("ks-Sink");
    setSpacing(15);

    message1 = new Label("Welcome to the PolicyGrid Data Archive.");
    message1.setStyleName("wysiwym-label-xlarge");
    message2 = new Label("Please upload your resource.");
    message2.setStyleName("wysiwym-label-large");

    VerticalPanel vp = new VerticalPanel();
    vp.add(message1);
    vp.add(message2);

    Image image = new Image();
    image.setUrl("http://www.csd.abdn.ac.uk/~fhielkem/logo.jpg");

    DockPanel top = new DockPanel();
    top.setWidth("100%");
    top.add(vp, DockPanel.WEST);
    top.add(image, DockPanel.EAST);
    add(top);

    form = new FormPanel();
    form.setAction(GWT.getModuleBaseURL() + "/postings?action=upload");
    form.setEncoding(FormPanel.ENCODING_MULTIPART);
    form.setMethod(FormPanel.METHOD_POST);
    form.setWidget(this);

    upload = new FileUpload();
    upload.setName("upload");
    add(upload);

    Hidden hid = new Hidden("user", parent.getUser());
    add(hid);

    add(
        new Button(
            "Next >>",
            new ClickListener() { // if user clicks next, submit the uploaded file
              public void onClick(Widget sender) {
                form.submit();
              }
            }));

    form.addFormHandler(
        new FormHandler() { // check whether resource was uploaded and stored in Fedora. If not,
                            // display error message.
          public void onSubmitComplete(
              FormSubmitCompleteEvent event) { // tell the parent to create the initial description
            if (event.getResults().indexOf("ERROR!!") >= 0)
              Window.alert(
                  "There was an error uploading your file. "
                      + "It may be because your filename is too long, or contains special characters. "
                      + "Please rename your file with a shorter name, using only letters and numbers, and try to upload it again.");
            else {
              RootPanel.get().remove(form);
              parent.startDescription(event.getResults());
            }
          }

          public void onSubmit(
              FormSubmitEvent
                  event) { // check whether user has uploaded a resource; if not, display warning
            if (upload.getFilename().length() == 0) {
              Window.alert("Please upload a document first.");
              event.setCancelled(true);
            }
          }
        });
    RootPanel.get().add(form);
  }
コード例 #22
0
 @Override
 public void createWidget() {
   descriptionLabel = new HTML(this.description);
   fileUpload = new FileUpload();
   fileUpload.setName("uploadFormElement_" + description);
 }
コード例 #23
0
 @UiHandler(value = {"uploadModuleFileUpload"})
 void changeUploadModulePathLabel(ChangeEvent event) {
   uploadModulePathLabel.setText(uploadModuleFileUpload.getFilename());
 }
コード例 #24
0
  public StateEditarPerfil(EstradaSolidariaServiceAsync estradaSolidariaService, String[] result) {
    this.estradaService = estradaSolidariaService;
    this.idSessaoAberta = EstradaSolidaria.getIdSessaoAberta();
    this.dadosUsuario = result;

    Resources resources = GWT.create(Resources.class);

    AbsolutePanel absolutePanel_EditarPerfil = new AbsolutePanel();
    absolutePanel_EditarPerfil.setStylePrimaryName("painelPerfil3");
    initWidget(absolutePanel_EditarPerfil);
    absolutePanel_EditarPerfil.setSize("873px", "433px");

    Label lblEditarPerfil = new Label("Editar Perfil");
    lblEditarPerfil.setStyleName("gwt-LabelEstradaSolidaria2");
    absolutePanel_EditarPerfil.add(lblEditarPerfil, 183, 10);

    AbsolutePanel absolutePanel_1 = new AbsolutePanel();
    absolutePanel_EditarPerfil.add(absolutePanel_1, 54, 48);
    absolutePanel_1.setSize("812px", "375px");

    Label lblNewLabel = new Label("Login:"******"Editar");
    absolutePanel_1.add(txtBtnEditarLogin, 84, 32);

    textBoxNovoLogin = new TextBox();
    textBoxNovoLogin.addKeyPressHandler(
        new KeyPressHandler() {
          public void onKeyPress(KeyPressEvent event) {
            lblMensagemDeErroLogin.setVisible(false);
          }
        });
    absolutePanel_1.add(textBoxNovoLogin, 145, 32);
    textBoxNovoLogin.setVisible(false);

    txtbtnLoginOk = new TextButton("OK");
    txtbtnLoginOk.addClickHandler(
        new ClickHandler() {
          public void onClick(ClickEvent event) {
            editarLoginGUI(idSessaoAberta, textBoxNovoLogin.getText());
          }
        });
    absolutePanel_1.add(txtbtnLoginOk, 306, 32);
    txtbtnLoginOk.setVisible(false);

    Label lblSenha = new Label("Senha:");
    absolutePanel_1.add(lblSenha, 473, 10);

    TextButton txtbtnAlterarSenha = new TextButton("Alterar senha");
    txtbtnAlterarSenha.addClickHandler(
        new ClickHandler() {
          public void onClick(ClickEvent event) {
            DialogBox newDialog = new DialogBoxAlterarSenha(estradaService);
            newDialog.center();
            newDialog.show();
          }
        });
    absolutePanel_1.add(txtbtnAlterarSenha, 473, 32);

    Label lblNome = new Label("Nome:");
    absolutePanel_1.add(lblNome, 10, 85);

    lblNomeusuario = new Label(dadosUsuario[2]);
    absolutePanel_1.add(lblNomeusuario, 74, 85);

    TextButton btnEditarNome = new TextButton("Editar");
    absolutePanel_1.add(btnEditarNome, 85, 107);

    textBoxNovoNome = new TextBox();
    textBoxNovoNome.addKeyPressHandler(
        new KeyPressHandler() {
          public void onKeyPress(KeyPressEvent event) {
            lblMensagemDeErroNome.setVisible(false);
          }
        });
    absolutePanel_1.add(textBoxNovoNome, 145, 107);
    textBoxNovoNome.setVisible(false);

    txtbtnNomeOk = new TextButton("OK");
    txtbtnNomeOk.addClickHandler(
        new ClickHandler() {
          public void onClick(ClickEvent event) {
            editarNomeGUI(idSessaoAberta, textBoxNovoNome.getText());
          }
        });
    absolutePanel_1.add(txtbtnNomeOk, 306, 107);
    txtbtnNomeOk.setVisible(false);

    Label lblEmail = new Label("Email:");
    absolutePanel_1.add(lblEmail, 10, 164);

    lblEmaildousuario = new Label(dadosUsuario[4]);
    absolutePanel_1.add(lblEmaildousuario, 74, 164);

    TextButton btnEditarEmail = new TextButton("Editar");
    absolutePanel_1.add(btnEditarEmail, 85, 184);

    textBoxNovoEmail = new TextBox();
    textBoxNovoEmail.addKeyPressHandler(
        new KeyPressHandler() {
          public void onKeyPress(KeyPressEvent event) {
            lblMensagemDeErroEmail.setVisible(false);
          }
        });
    absolutePanel_1.add(textBoxNovoEmail, 145, 184);
    textBoxNovoEmail.setVisible(false);

    txtbtnEmailOk = new TextButton("OK");
    txtbtnEmailOk.addClickHandler(
        new ClickHandler() {
          public void onClick(ClickEvent event) {
            editarEmailGUI(idSessaoAberta, textBoxNovoEmail.getText());
          }
        });
    absolutePanel_1.add(txtbtnEmailOk, 306, 184);
    txtbtnEmailOk.setVisible(false);

    Label lblEndereo = new Label("Endereço:");
    absolutePanel_1.add(lblEndereo, 9, 243);

    lblEnderecodousuario = new Label(dadosUsuario[3]);
    absolutePanel_1.add(lblEnderecodousuario, 74, 243);

    TextButton btnEditarEndereco = new TextButton("Editar");
    absolutePanel_1.add(btnEditarEndereco, 85, 265);

    textBoxNovoEndereco = new TextBox();
    textBoxNovoEndereco.addKeyPressHandler(
        new KeyPressHandler() {
          public void onKeyPress(KeyPressEvent event) {
            lblMensagemDeErroEndereco.setVisible(false);
          }
        });
    absolutePanel_1.add(textBoxNovoEndereco, 145, 265);
    textBoxNovoEndereco.setVisible(false);

    txtbtnEnderecoOk = new TextButton("OK");
    txtbtnEnderecoOk.addClickHandler(
        new ClickHandler() {
          public void onClick(ClickEvent event) {
            editarEnderecoGUI(idSessaoAberta, textBoxNovoEndereco.getText());
          }
        });
    absolutePanel_1.add(txtbtnEnderecoOk, 306, 265);
    txtbtnEnderecoOk.setVisible(false);

    FileUpload fileUpload = new FileUpload();
    absolutePanel_1.add(fileUpload, 473, 319);
    fileUpload.setSize("330px", "22px");

    Image image = new Image(resources.getGenericUserImage());
    absolutePanel_1.add(image, 473, 174);
    image.setSize("126px", "139px");

    lblMensagemDeErroLogin = new Label("erro login");
    lblMensagemDeErroLogin.setStyleName("gwt-LabelEstradaSolidaria5");
    absolutePanel_1.add(lblMensagemDeErroLogin, 145, 62);
    lblMensagemDeErroLogin.setVisible(false);

    lblMensagemDeErroNome = new Label("erro nome");
    lblMensagemDeErroNome.setStyleName("gwt-LabelEstradaSolidaria5");
    absolutePanel_1.add(lblMensagemDeErroNome, 145, 141);
    lblMensagemDeErroNome.setVisible(false);

    lblMensagemDeErroEmail = new Label("erro email");
    lblMensagemDeErroEmail.setStyleName("gwt-LabelEstradaSolidaria5");
    absolutePanel_1.add(lblMensagemDeErroEmail, 145, 218);
    lblMensagemDeErroEmail.setVisible(false);

    lblMensagemDeErroEndereco = new Label("erro endereco");
    lblMensagemDeErroEndereco.setStyleName("gwt-LabelEstradaSolidaria5");
    absolutePanel_1.add(lblMensagemDeErroEndereco, 145, 297);
    lblMensagemDeErroEndereco.setVisible(false);

    btnEditarEndereco.addClickHandler(
        new ClickHandler() {
          public void onClick(ClickEvent event) {
            textBoxNovoEndereco.setVisible(true);
            txtbtnEnderecoOk.setVisible(true);
          }
        });

    btnEditarEmail.addClickHandler(
        new ClickHandler() {
          public void onClick(ClickEvent event) {
            textBoxNovoEmail.setVisible(true);
            txtbtnEmailOk.setVisible(true);
          }
        });

    btnEditarNome.addClickHandler(
        new ClickHandler() {
          public void onClick(ClickEvent event) {
            textBoxNovoNome.setVisible(true);
            txtbtnNomeOk.setVisible(true);
          }
        });

    txtBtnEditarLogin.addClickHandler(
        new ClickHandler() {
          public void onClick(ClickEvent event) {
            textBoxNovoLogin.setVisible(true);
            txtbtnLoginOk.setVisible(true);
          }
        });
  }
コード例 #25
0
ファイル: GusListView.java プロジェクト: hvidsten/guslist-gae
  // Helper method to create the internals of the HTML Form (FormPanel)
  //  Submit form may be for new post, or for editing existing post
  private FormPanel makeSubmitPostForm(final PostData post) {
    final FormPanel submitFormPanel = new FormPanel();
    VerticalPanel postFormPanel = new VerticalPanel();
    postFormPanel.addStyleName("submitPostVertPanel");
    submitFormPanel.add(postFormPanel);

    // Name input
    HorizontalPanel nameRow = new HorizontalPanel();
    Label nameLabel = new Label("Name (First Last");
    final TextBox nameTextbox = new TextBox();
    nameRow.add(nameLabel);
    nameRow.add(nameTextbox);
    postFormPanel.add(nameRow);

    // Title input
    HorizontalPanel titleRow = new HorizontalPanel();
    Label titleLabel = new Label("Title (e.g. car, bike, etc)");
    final TextBox titleTextbox = new TextBox();
    titleRow.add(titleLabel);
    titleRow.add(titleTextbox);
    postFormPanel.add(titleRow);

    // Description input
    HorizontalPanel descrRow = new HorizontalPanel();
    Label descrLabel = new Label("Item Short description");
    final TextArea descrText = new TextArea();
    descrText.setCharacterWidth(40);
    descrText.setVisibleLines(10);
    descrRow.add(descrLabel);
    descrRow.add(descrText);
    postFormPanel.add(descrRow);

    // Price input
    HorizontalPanel priceRow = new HorizontalPanel();
    Label priceLabel = new Label("Price ($)");
    final TextBox priceTextbox = new TextBox();
    priceTextbox.setVisibleLength(6);
    priceRow.add(priceLabel);
    priceRow.add(priceTextbox);
    postFormPanel.add(priceRow);

    // Address input
    HorizontalPanel addressRow = new HorizontalPanel();
    Label addressLabel = new Label("Address");
    final TextArea addressText = new TextArea();
    addressText.setCharacterWidth(40);
    addressText.setVisibleLines(5);
    addressRow.add(addressLabel);
    addressRow.add(addressText);
    postFormPanel.add(addressRow);

    if (post != null) {
      nameTextbox.setText(post.getSellerName());
      titleTextbox.setText(post.getTitle());
      descrText.setText(post.getDescription());
      priceTextbox.setText("" + post.getPrice());
      addressText.setText(post.getAddress());
    }

    // New widget for file upload
    HorizontalPanel fileRow = new HorizontalPanel();
    final FileUpload upload = new FileUpload();
    if (post != null) {
      Anchor link = new Anchor("Stored File", post.getURL());
      link.setTarget("_blank");
      fileRow.add(link);
      upload.setTitle("Change Uploaded File");
    } else upload.setTitle("Upload a File for Post");
    fileRow.add(upload);
    postFormPanel.add(fileRow);

    // Submit button
    Button submitButton;
    if (post != null) {
      submitButton = new Button("Submit Changes");
      submitButton.setText("Submit Changes");
    } else {
      submitButton = new Button("Submit Ad");
      submitButton.setText("Submit Ad");
    }
    submitButton.setStyleName("sideBarButton");
    postFormPanel.add(submitButton);

    // The submitFormPanel, when submitted, will trigger an HTTP call to the
    // servlet.  The following parameters must be set
    submitFormPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
    submitFormPanel.setMethod(FormPanel.METHOD_POST);

    // Set Names for the text boxes so that they can be retrieved from the
    // HTTP call as parameters
    nameTextbox.setName("name");
    titleTextbox.setName("title");
    descrText.setName("description");
    priceTextbox.setName("price");
    addressText.setName("address");
    upload.setName("upload");

    // Upon clicking "Submit" control goes to Controller
    submitButton.addClickHandler(
        new ClickHandler() {
          public void onClick(ClickEvent event) {
            if (post == null) control.handlePostFromSubmitForm(submitFormPanel);
            else control.handlePostEditFromSubmitForm(post, submitFormPanel);
          }
        });

    // This event handler is "fired" just before the Form causes a doPost
    //  message to server
    submitFormPanel.addSubmitHandler(
        new FormPanel.SubmitHandler() {
          public void onSubmit(SubmitEvent event) {
            // This event is fired just before the form is submitted.
            //  We can take this opportunity to perform validation.
            if (nameTextbox.getText().length() == 0) {
              Window.alert("The author is required.");
              event.cancel();
            }
            if (titleTextbox.getText().length() == 0) {
              Window.alert("The title is required.");
              event.cancel();
            }
            Double price = Double.parseDouble(priceTextbox.getText());
            if (priceTextbox.getText().length() == 0 || Double.isNaN(price)) {
              Window.alert("The price is required. It must be a valid number");
              event.cancel();
            }
            if (addressText.getText().length() == 0) {
              Window.alert("The address is required.");
              event.cancel();
            }
            if (upload.getFilename().length() == 0 && post == null) {
              Window.alert("The upload file is required.");
              event.cancel();
            }
          }
        });

    // The doPost message itself is sent from the Form and not intercepted
    //  by GWT.

    // This event handler is "fired" just after the Form causes a doPost
    //  message to server
    submitFormPanel.addSubmitCompleteHandler(
        new FormPanel.SubmitCompleteHandler() {
          public void onSubmitComplete(SubmitCompleteEvent event) {
            if (post == null) {
              submitFormPanel.reset();
              nameTextbox.setFocus(true);
            } else control.viewAdDataFromServer();
          }
        });
    return submitFormPanel;
  }
コード例 #26
0
ファイル: DeploymentStep1.java プロジェクト: jsight/core-1
  public Widget asWidget() {

    final TabPanel tabs = new TabPanel();
    tabs.setStyleName("default-tabpanel");

    // -------

    VerticalPanel layout = new VerticalPanel();
    layout.setStyleName("window-content");

    // Create a FormPanel and point it at a service.
    final FormPanel form = new FormPanel();
    String url = Console.getBootstrapContext().getProperty(BootstrapContext.DEPLOYMENT_API);
    form.setAction(url);

    form.setEncoding(FormPanel.ENCODING_MULTIPART);
    form.setMethod(FormPanel.METHOD_POST);

    // Create a panel to hold all of the form widgets.
    VerticalPanel panel = new VerticalPanel();
    panel.getElement().setAttribute("style", "width:100%");
    form.setWidget(panel);

    // Create a FileUpload widgets.
    final FileUpload upload = new FileUpload();
    upload.setName("uploadFormElement");
    panel.add(upload);

    final HTML errorMessages = new HTML("Please chose a file!");
    errorMessages.setStyleName("error-panel");
    errorMessages.setVisible(false);
    panel.add(errorMessages);

    // Add a 'submit' button.

    ClickHandler cancelHandler =
        new ClickHandler() {
          @Override
          public void onClick(ClickEvent event) {
            window.hide();
          }
        };

    ClickHandler submitHandler =
        new ClickHandler() {
          @Override
          public void onClick(ClickEvent event) {

            errorMessages.setVisible(false);

            // verify form
            String filename = upload.getFilename();

            if (tabs.getTabBar().getSelectedTab() == 1) {
              // unmanaged content
              if (unmanagedForm.validate().hasErrors()) {
                return;
              } else {
                wizard.onCreateUnmanaged(unmanagedForm.getUpdatedEntity());
              }
            } else if (filename != null && !filename.equals("")) {
              loading =
                  Feedback.loading(
                      Console.CONSTANTS.common_label_plaseWait(),
                      Console.CONSTANTS.common_label_requestProcessed(),
                      new Feedback.LoadingCallback() {
                        @Override
                        public void onCancel() {}
                      });
              form.submit();
            } else {
              errorMessages.setVisible(true);
            }
          }
        };

    DialogueOptions options =
        new DialogueOptions(
            Console.CONSTANTS.common_label_next(), submitHandler,
            Console.CONSTANTS.common_label_cancel(), cancelHandler);

    // Add an event handler to the form.
    form.addSubmitCompleteHandler(
        new FormPanel.SubmitCompleteHandler() {
          @Override
          public void onSubmitComplete(FormPanel.SubmitCompleteEvent event) {

            getLoading().hide();

            String html = event.getResults();

            // Step 1: upload content, retrieve hash value
            try {

              String json = html;

              try {
                if (!GWT.isScript()) // TODO: Formpanel weirdness
                json = html.substring(html.indexOf(">") + 1, html.lastIndexOf("<"));
              } catch (StringIndexOutOfBoundsException e) {
                // if I get this exception it means I shouldn't strip out the html
                // this issue still needs more research
                Log.debug("Failed to strip out HTML.  This should be preferred?");
              }

              JSONObject response = JSONParser.parseLenient(json).isObject();
              JSONObject result = response.get("result").isObject();
              String hash = result.get("BYTES_VALUE").isString().stringValue();
              // step2: assign name and group
              wizard.onUploadComplete(upload.getFilename(), hash);

            } catch (Exception e) {
              Log.error(Console.CONSTANTS.common_error_failedToDecode() + ": " + html, e);
            }

            // Option 2: Unmanaged content

          }
        });

    String stepText =
        "<h3>"
            + Console.CONSTANTS.common_label_step()
            + "1/2: "
            + Console.CONSTANTS.common_label_deploymentSelection()
            + "</h3>";
    layout.add(new HTML(stepText));
    HTML description = new HTML();
    description.setHTML(Console.CONSTANTS.common_label_chooseFile());
    description.getElement().setAttribute("style", "padding-bottom:15px;");
    layout.add(description);
    layout.add(form);
    tabs.add(layout, "Managed");

    // Unmanaged form only for new deployments
    if (!wizard.isUpdate()) {
      VerticalPanel unmanagedPanel = new VerticalPanel();
      unmanagedPanel.setStyleName("window-content");

      String unmanagedText =
          "<h3>" + Console.CONSTANTS.common_label_step() + "1/1: Specify Deployment</h3>";
      unmanagedPanel.add(new HTML(unmanagedText));

      unmanagedForm = new Form<DeploymentRecord>(DeploymentRecord.class);
      TextAreaItem path = new TextAreaItem("path", "Path");
      TextBoxItem relativeTo = new TextBoxItem("relativeTo", "Relative To", false);

      TextBoxItem name = new TextBoxItem("name", "Name");
      TextBoxItem runtimeName = new TextBoxItem("runtimeName", "Runtime Name");
      CheckBoxItem archive = new CheckBoxItem("archive", "Is Archive?");
      archive.setValue(true);
      unmanagedForm.setFields(path, relativeTo, archive, name, runtimeName);
      unmanagedPanel.add(unmanagedForm.asWidget());
      tabs.add(unmanagedPanel, "Unmanaged");
    }

    tabs.selectTab(0);
    return new WindowContentBuilder(tabs, options).build();
  }
コード例 #27
0
  private void createComponent() {
    hlBack = new Anchor("<<back");
    hlBack.addClickHandler(this);
    vPanel.add(hlBack);
    ProjectItems projectItems = currentUser.getProjectItems();
    if (projectItems.getProjectItemCount() == 0) {
      vPanel.add(new HTML("You are not subscribed to any projects."));
    } else {
      vPanel.add(form);
      lbProjects = new ListBox(false);
      lbProjects.addChangeHandler(this);
      vPanel.setSize("1000px", "500px");
      table.setCellSpacing(5);
      table.setCellPadding(0);
      table.setWidth("100%");
      tbName.setWidth("300px");
      // tbDescription.setWidth("300px");
      txtFileNotes.setHeight("75px");
      upload.setName("uploadFormElement");
      // fileUpload.setName("fileuploadFormElement");
      tbName.setName("name");
      tbDescription.setName("description");
      txtFileNotes.setName("notes");
      lbProjects.setName("projectDetails");
      btnSubmit.addClickHandler(this);
      txtWarnings.setStylePrimaryName("warnings");
      txtWarningDesc.setStylePrimaryName("warnings");
      txtFileNotes.setCharacterWidth(50);
      tbName.setMaxLength(50);
      // tbDescription.setMaxLength(255);
      // tbDescription.setText("");
      txtLogin = new TextBox();
      txtLogin.setName("user");
      txtLogin.setVisible(false);

      txtProject = new TextBox();
      txtProject.setName("projectName");
      txtProject.setVisible(false);

      int projectId = currentUser.getPreferredProjectId();

      for (int i = 0; i < projectItems.getProjectItemCount(); i++) {
        ProjectItem item = projectItems.getProjectItem(i);
        lbProjects.addItem(item.getProjectName(), String.valueOf(item.getProjectId()));
        if (projectId > 0) {
          if (projectId == item.getProjectId()) {
            lbProjects.setItemSelected(i, true);
          }
        } else {
          lbProjects.setItemSelected(0, true);
        }
      }

      table.setText(0, 0, "");
      table.setWidget(0, 1, txtWarnings);
      table.setText(1, 0, "");
      table.setWidget(1, 1, txtWarningDesc);
      table.setWidget(2, 0, new HTML("<b>Name:</b>&nbsp;&nbsp;&nbsp;"));
      table.setWidget(2, 1, tbName);
      table.setWidget(3, 0, new HTML("<b>File:</b>&nbsp;&nbsp;&nbsp;"));
      table.setWidget(3, 1, upload);
      // table.setWidget(4, 0, new HTML("<b>Description:</b>&nbsp;&nbsp;&nbsp;"));
      // table.setWidget(4, 1, fileUpload);
      table.setWidget(5, 0, new HTML("<b>Project:</b>&nbsp;&nbsp;&nbsp;"));
      table.setWidget(5, 1, lbProjects);
      table.setWidget(6, 0, new HTML("<b>Notes:</b>&nbsp;&nbsp;&nbsp;"));
      table.setWidget(6, 1, txtFileNotes);
      table.setWidget(7, 1, btnSubmit);
      table.setWidget(7, 2, txtLogin);
      table.setWidget(7, 3, txtProject);

      table.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_RIGHT);
      table.getCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_RIGHT);
      table.getCellFormatter().setVerticalAlignment(1, 0, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(2, 0, HasHorizontalAlignment.ALIGN_RIGHT);
      table.getCellFormatter().setVerticalAlignment(2, 0, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(3, 0, HasHorizontalAlignment.ALIGN_RIGHT);
      table.getCellFormatter().setVerticalAlignment(3, 0, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(4, 0, HasHorizontalAlignment.ALIGN_RIGHT);
      table.getCellFormatter().setVerticalAlignment(4, 0, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(5, 0, HasHorizontalAlignment.ALIGN_RIGHT);
      table.getCellFormatter().setVerticalAlignment(5, 0, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(6, 0, HasHorizontalAlignment.ALIGN_RIGHT);
      table.getCellFormatter().setVerticalAlignment(6, 0, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(7, 0, HasHorizontalAlignment.ALIGN_RIGHT);
      table.getCellFormatter().setVerticalAlignment(7, 0, HasVerticalAlignment.ALIGN_TOP);

      table.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_LEFT);
      table.getCellFormatter().setVerticalAlignment(0, 1, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(1, 1, HasHorizontalAlignment.ALIGN_LEFT);
      table.getCellFormatter().setVerticalAlignment(1, 1, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(2, 1, HasHorizontalAlignment.ALIGN_LEFT);
      table.getCellFormatter().setVerticalAlignment(2, 1, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(3, 1, HasHorizontalAlignment.ALIGN_LEFT);
      table.getCellFormatter().setVerticalAlignment(3, 1, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(4, 1, HasHorizontalAlignment.ALIGN_LEFT);
      table.getCellFormatter().setVerticalAlignment(4, 1, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(5, 1, HasHorizontalAlignment.ALIGN_LEFT);
      table.getCellFormatter().setVerticalAlignment(5, 1, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(6, 1, HasHorizontalAlignment.ALIGN_LEFT);
      table.getCellFormatter().setVerticalAlignment(6, 1, HasVerticalAlignment.ALIGN_TOP);
      table.getCellFormatter().setHorizontalAlignment(7, 1, HasHorizontalAlignment.ALIGN_LEFT);
      table.getCellFormatter().setVerticalAlignment(7, 1, HasVerticalAlignment.ALIGN_TOP);

      form.add(table);

      form.setAction(UPLOAD_ACTION_URL);
      form.setEncoding(FormPanel.ENCODING_MULTIPART);
      form.setMethod(FormPanel.METHOD_POST);

      form.addSubmitHandler(
          new FormPanel.SubmitHandler() {
            public void onSubmit(SubmitEvent event) {
              // This event is fired just before the form is submitted. We can
              // take this opportunity to perform validation.
              String fileName1 = upload.getFilename().trim();
              // String fileName2 = fileUpload.getFilename().trim();
              // System.out.println("File1: " + fileName1);
              if (fileName1.length() == 0 && tbName.getText().length() == 0) {
                txtWarnings.setHTML("*Please upload a file.");
                txtWarningDesc.setHTML("*Please enter the Job name.");
                event.cancel();
              }
              if ((fileName1.length() == 0) && tbName.getText().length() != 0) {
                txtWarnings.setText("");
                txtWarningDesc.setText("");
                txtWarnings.setHTML("*Please upload a file.");
                event.cancel();
              }
              if ((!(fileName1.length() == 0)) && tbName.getText().length() == 0) {
                txtWarnings.setText("");
                txtWarningDesc.setText("");
                txtWarnings.setHTML("*Please enter the Job name.");
                event.cancel();
              }
            }
          });

      form.addSubmitCompleteHandler(
          new FormPanel.SubmitCompleteHandler() {
            public void onSubmitComplete(SubmitCompleteEvent event) {
              txtFileNotes.setText("");
              txtWarningDesc.setText("");
              String sessionID = Cookies.getCookie("sid");
              if (sessionID != null) {
                String result = event.getResults();
                System.out.println("UploadJob Result: " + result);
                // Log.info("Result: " + result);
                String[] results = result.split("~");
                /*for(int i = 0; i < results.length; i++)
                {
                	 System.out.println(results[i]);
                	 try
                	 {
                		 jobId = Integer.parseInt(results[0]);
                	 }
                	 catch(NumberFormatException e)
                	 {
                		 e.printStackTrace();
                	 }
                }*/
                int jobId = -1;
                try {
                  jobId = Integer.parseInt(results[0]);
                } catch (NumberFormatException e) {
                  e.printStackTrace();
                }
                // Code modified
                if (jobId == 0) {
                  txtWarnings.setHTML(results[1]);
                }
                // Code modified
                // txtWarnings.setHTML(results[1]);

                else {
                  if (currentUser.getUsertype().equalsIgnoreCase("user")) {
                    History.newItem("userJobList");
                  } else {
                    if (tab == 0) {

                      History.newItem("adminJobList");
                    } else {
                      History.newItem("jobList");
                    }
                    // AdminPage adminPage = new AdminPage(tab);
                    // RootPanel.get("content").add(adminPage);
                  }
                }
              } else {
                Login login = new Login();
                login.displayLoginBox();
              }
            }
          });
    }
  }
コード例 #28
0
ファイル: SeletorFoto.java プロジェクト: breakfast/tomorrow
 public static String getPathFoto() {
   init();
   popup.show();
   return fileUpload.getFilename();
 }
コード例 #29
0
  /** @param repositoryFile */
  public ImportDialog(RepositoryFile repositoryFile, boolean allowAdvancedDialog) {
    super(
        Messages.getString("import"),
        Messages.getString("ok"),
        Messages.getString("cancel"),
        false,
        true); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    form = new FormPanel();
    form.addSubmitHandler(
        new SubmitHandler() {
          @Override
          public void onSubmit(SubmitEvent se) {
            // if no file is selected then do not proceed
            okButton.setEnabled(false);
            cancelButton.setEnabled(false);
            MantleApplication.showBusyIndicator(
                Messages.getString("pleaseWait"), Messages.getString("importInProgress"));
          }
        });
    form.addSubmitCompleteHandler(
        new SubmitCompleteHandler() {
          @Override
          public void onSubmitComplete(SubmitCompleteEvent sce) {
            MantleApplication.hideBusyIndicator();
            okButton.setEnabled(false);
            cancelButton.setEnabled(true);
            ImportDialog.this.hide();
            String result = sce.getResults();
            if (result.length() > 5) {
              HTML messageTextBox = null;
              if (result.contains("INVALID_MIME_TYPE") == true) {
                messageTextBox =
                    new HTML(Messages.getString("uploadInvalidFileTypeQuestion", result));
              } else {
                logWindow(result, Messages.getString("importLogWindowTitle"));
              }

              if (messageTextBox != null) {
                PromptDialogBox dialogBox =
                    new PromptDialogBox(
                        Messages.getString("uploadUnsuccessful"),
                        Messages.getString("close"),
                        null,
                        true,
                        true);
                dialogBox.setContent(messageTextBox);
                dialogBox.center();
              }
            }

            // if mantle_isBrowseRepoDirty=true: do getChildren call
            // if mantle_isBrowseRepoDirty=false: use stored fileBrowserModel in
            // myself.get("cachedData")
            setBrowseRepoDirty(Boolean.TRUE);

            // BISERVER-9319 Refresh browse perspective after import
            final GenericEvent event = new GenericEvent();
            event.setEventSubType("ImportDialogEvent");
            EventBusUtil.EVENT_BUS.fireEvent(event);
          }
        });

    VerticalPanel rootPanel = new VerticalPanel();

    VerticalPanel spacer = new VerticalPanel();
    spacer.setHeight("10px");
    rootPanel.add(spacer);

    Label fileLabel = new Label(Messages.getString("file") + ":");
    final TextBox importDir = new TextBox();
    rootPanel.add(fileLabel);

    okButton.setEnabled(false);

    final TextBox fileTextBox = new TextBox();
    fileTextBox.setHeight("26px");
    fileTextBox.setEnabled(false);

    // We use an fileNameOverride because FileUpload can only handle US character set reliably.
    final Hidden fileNameOverride = new Hidden("fileNameOverride");

    final FileUpload upload = new FileUpload();
    upload.setName("fileUpload");
    ChangeHandler fileUploadHandler =
        new ChangeHandler() {
          @Override
          public void onChange(ChangeEvent event) {
            fileTextBox.setText(upload.getFilename());
            if (!"".equals(importDir.getValue())) {
              // Set the fileNameOverride because the fileUpload object can only reliably transmit
              // US-ASCII
              // character set.  See RFC283 section 2.3 for details
              String fileNameValue = upload.getFilename().replaceAll("\\\\", "/");
              fileNameValue = fileNameValue.substring(fileNameValue.lastIndexOf("/") + 1);
              fileNameOverride.setValue(fileNameValue);
              okButton.setEnabled(true);
            } else {
              okButton.setEnabled(false);
            }
          }
        };
    upload.addChangeHandler(fileUploadHandler);
    upload.setVisible(false);

    HorizontalPanel fileUploadPanel = new HorizontalPanel();
    fileUploadPanel.add(fileTextBox);
    fileUploadPanel.add(new HTML("&nbsp;"));

    Button browseButton = new Button(Messages.getString("browse") + "...");
    browseButton.setStyleName("pentaho-button");
    fileUploadPanel.add(browseButton);
    browseButton.addClickHandler(
        new ClickHandler() {
          @Override
          public void onClick(ClickEvent event) {
            setRetainOwnershipState();
            jsClickUpload(upload.getElement());
          }
        });

    rootPanel.add(fileUploadPanel);
    rootPanel.add(upload);

    applyAclPermissions.setName("applyAclPermissions");
    applyAclPermissions.setValue(Boolean.FALSE);
    applyAclPermissions.setFormValue("false");
    applyAclPermissions.setEnabled(true);
    applyAclPermissions.setVisible(false);

    final CheckBox overwriteAclPermissions =
        new CheckBox(Messages.getString("overwriteAclPermissions"), true);
    overwriteAclPermissions.setName("overwriteAclPermissions");
    applyAclPermissions.setValue(Boolean.FALSE);
    applyAclPermissions.setFormValue("false");
    overwriteAclPermissions.setEnabled(true);
    overwriteAclPermissions.setVisible(false);

    final Hidden overwriteFile = new Hidden("overwriteFile");
    overwriteFile.setValue("true");

    final Hidden logLevel = new Hidden("logLevel");
    logLevel.setValue("ERROR");

    final Hidden retainOwnership = new Hidden("retainOwnership");
    retainOwnership.setValue("true");

    rootPanel.add(applyAclPermissions);
    rootPanel.add(overwriteAclPermissions);
    rootPanel.add(overwriteFile);
    rootPanel.add(logLevel);
    rootPanel.add(retainOwnership);
    rootPanel.add(fileNameOverride);

    spacer = new VerticalPanel();
    spacer.setHeight("4px");
    rootPanel.add(spacer);

    DisclosurePanel disclosurePanel = new DisclosurePanel(Messages.getString("advancedOptions"));
    disclosurePanel.getHeader().setStyleName("gwt-Label");
    disclosurePanel.setVisible(allowAdvancedDialog);
    HorizontalPanel mainPanel = new HorizontalPanel();
    mainPanel.add(new HTML("&nbsp;"));
    VerticalPanel disclosureContent = new VerticalPanel();

    HTML replaceLabel = new HTML(Messages.getString("fileExists"));
    replaceLabel.setStyleName("gwt-Label");
    disclosureContent.add(replaceLabel);

    final CustomListBox overwriteFileDropDown = new CustomListBox();
    final CustomListBox filePermissionsDropDown = new CustomListBox();

    DefaultListItem replaceListItem = new DefaultListItem(Messages.getString("replaceFile"));
    replaceListItem.setValue("true");
    overwriteFileDropDown.addItem(replaceListItem);
    DefaultListItem doNotImportListItem = new DefaultListItem(Messages.getString("doNotImport"));
    doNotImportListItem.setValue("false");
    overwriteFileDropDown.addItem(doNotImportListItem);
    overwriteFileDropDown.setVisibleRowCount(1);
    disclosureContent.add(overwriteFileDropDown);

    spacer = new VerticalPanel();
    spacer.setHeight("4px");
    disclosureContent.add(spacer);

    HTML filePermissionsLabel = new HTML(Messages.getString("filePermissions"));
    filePermissionsLabel.setStyleName("gwt-Label");
    disclosureContent.add(filePermissionsLabel);

    DefaultListItem usePermissionsListItem =
        new DefaultListItem(Messages.getString("usePermissions"));
    usePermissionsListItem.setValue("false");
    filePermissionsDropDown.addItem(
        usePermissionsListItem); // If selected set "overwriteAclPermissions" to
    // false.
    DefaultListItem retainPermissionsListItem =
        new DefaultListItem(Messages.getString("retainPermissions"));
    retainPermissionsListItem.setValue("true");
    filePermissionsDropDown.addItem(
        retainPermissionsListItem); // If selected set "overwriteAclPermissions" to
    // true.

    final ChangeListener filePermissionsHandler =
        new ChangeListener() {
          @Override
          public void onChange(Widget sender) {
            String value = filePermissionsDropDown.getSelectedItem().getValue().toString();

            applyAclPermissions.setValue(Boolean.valueOf(value));
            applyAclPermissions.setFormValue(value);
            overwriteAclPermissions.setFormValue(value);
            overwriteAclPermissions.setValue(Boolean.valueOf(value));
            setRetainOwnershipState();
          }
        };
    filePermissionsDropDown.addChangeListener(filePermissionsHandler);
    filePermissionsDropDown.setVisibleRowCount(1);
    disclosureContent.add(filePermissionsDropDown);

    spacer = new VerticalPanel();
    spacer.setHeight("4px");
    disclosureContent.add(spacer);

    HTML fileOwnershipLabel = new HTML(Messages.getString("fileOwnership"));
    fileOwnershipLabel.setStyleName("gwt-Label");
    disclosureContent.add(fileOwnershipLabel);

    retainOwnershipDropDown.addChangeListener(
        new ChangeListener() {
          @Override
          public void onChange(Widget sender) {
            String value = retainOwnershipDropDown.getSelectedItem().getValue().toString();
            retainOwnership.setValue(value);
          }
        });
    DefaultListItem keepOwnershipListItem =
        new DefaultListItem(Messages.getString("keepOwnership"));
    keepOwnershipListItem.setValue("true");
    retainOwnershipDropDown.addItem(keepOwnershipListItem);
    DefaultListItem assignOwnershipListItem =
        new DefaultListItem(Messages.getString("assignOwnership"));
    assignOwnershipListItem.setValue("false");
    retainOwnershipDropDown.addItem(assignOwnershipListItem);

    retainOwnershipDropDown.setVisibleRowCount(1);
    disclosureContent.add(retainOwnershipDropDown);

    spacer = new VerticalPanel();
    spacer.setHeight("4px");
    disclosureContent.add(spacer);

    ChangeListener overwriteFileHandler =
        new ChangeListener() {
          @Override
          public void onChange(Widget sender) {
            String value = overwriteFileDropDown.getSelectedItem().getValue().toString();
            overwriteFile.setValue(value);
          }
        };
    overwriteFileDropDown.addChangeListener(overwriteFileHandler);

    HTML loggingLabel = new HTML(Messages.getString("logging"));
    loggingLabel.setStyleName("gwt-Label");
    disclosureContent.add(loggingLabel);

    final CustomListBox loggingDropDown = new CustomListBox();
    loggingDropDown.addChangeListener(
        new ChangeListener() {
          public void onChange(Widget sender) {
            String value = loggingDropDown.getSelectedItem().getValue().toString();
            logLevel.setValue(value);
          }
        });
    DefaultListItem noneListItem = new DefaultListItem(Messages.getString("none"));
    noneListItem.setValue("ERROR");
    loggingDropDown.addItem(noneListItem);
    DefaultListItem shortListItem = new DefaultListItem(Messages.getString("short"));
    shortListItem.setValue("WARN");
    loggingDropDown.addItem(shortListItem);
    DefaultListItem debugListItem = new DefaultListItem(Messages.getString("verbose"));
    debugListItem.setValue("TRACE");
    loggingDropDown.addItem(debugListItem);
    loggingDropDown.setVisibleRowCount(1);
    disclosureContent.add(loggingDropDown);

    mainPanel.add(disclosureContent);
    disclosurePanel.setContent(mainPanel);
    rootPanel.add(disclosurePanel);

    importDir.setName("importDir");
    importDir.setText(repositoryFile.getPath());
    importDir.setVisible(false);

    rootPanel.add(importDir);

    form.setEncoding(FormPanel.ENCODING_MULTIPART);
    form.setMethod(FormPanel.METHOD_POST);

    setFormAction();

    form.add(rootPanel);

    setContent(form);
  }