Пример #1
0
  @Override
  void doSave() {

    int order;
    try {
      order = Integer.parseInt(listOrderEd.getText().trim());
    } catch (NumberFormatException e) {
      Window.alert(
          "Enter an integer to indicate the order that this season will appear in a drop down selection box");
      listOrderEd.setFocus(true);
      return;
    }
    if (seasonEd.getText().trim().length() == 0) {
      Window.alert("Enter a Season");
      return;
    }

    TSe season = new TSe();
    if (editRb.getValue()) {
      season.setId(getLookupId());
    }
    season.setListOrder(order);
    season.setSeason(seasonEd.getText());
    saveBtn.setEnabled(false);
    service.saveSeason(season);
  }
  private void applyChanges(
      final GenericColumnCommand refreshGrid,
      final ActionRetractFactCol52 col,
      final boolean isNew) {
    if (null == editingCol.getHeader() || "".equals(editingCol.getHeader())) {
      Window.alert(
          GuidedDecisionTableConstants.INSTANCE.YouMustEnterAColumnHeaderValueDescription());
      return;
    }
    if (isNew) {
      if (!unique(editingCol.getHeader())) {
        Window.alert(
            GuidedDecisionTableConstants.INSTANCE.ThatColumnNameIsAlreadyInUsePleasePickAnother());
        return;
      }

    } else {
      if (!col.getHeader().equals(editingCol.getHeader())) {
        if (!unique(editingCol.getHeader())) {
          Window.alert(
              GuidedDecisionTableConstants.INSTANCE
                  .ThatColumnNameIsAlreadyInUsePleasePickAnother());
          return;
        }
      }
    }

    // Pass new\modified column back for handling
    refreshGrid.execute(editingCol);
    hide();
  }
Пример #3
0
  /**
   * Exported the selected item.
   *
   * @param item Item to export.
   * @param eventListener <tt>Event Listener</tt> for the export operation.
   */
  public static void exportSelectedItem(
      TreeItem item, GetFileNameDialogEventListener eventListener) {
    if (item == null) {
      // TODO add message for internationalization purposes
      Window.alert("Please select the item to export.");
      return;
    }

    if (((Editable) item.getUserObject()).isNew()) {
      // TODO add message for internationalization purposes
      Window.alert("Please first save this item.");
      return;
    }

    String name = "";
    Object studyItem = item.getUserObject();
    if (studyItem instanceof StudyDef) name = ((StudyDef) studyItem).getName();
    else if (studyItem instanceof FormDef)
      name =
          ((StudyDef) item.getParentItem().getUserObject()).getName()
              + "-"
              + ((FormDef) studyItem).getName();
    else if (studyItem instanceof FormDefVersion)
      name =
          ((StudyDef) item.getParentItem().getParentItem().getUserObject()).getName()
              + "-"
              + ((FormDef) item.getParentItem().getUserObject()).getName()
              + "-"
              + ((FormDefVersion) studyItem).getName();

    name = name.replace(" ", "");
    new GetFileNameDialog(
            eventListener, constants.label_export_as(), constants.label_export(), name)
        .center();
  }
  private static boolean needToUpgrade(int srcYaVersion) {
    // Compare the source file's YoungAndroid version with the system's YoungAndroid version.
    final int sysYaVersion = YaVersion.YOUNG_ANDROID_VERSION;
    if (srcYaVersion > sysYaVersion) {
      // The source file's version is newer than the system's version.
      // This can happen if the user is using (or in the past has used) a non-production version of
      // App Inventor.
      // This can also happen if the user is connected to a new version of App Inventor and then
      // later is connected to an old version of App Inventor.
      // We'll try to load the project but there may be compatibility issues if the project uses
      // future components or other features that the current system doesn't understand.
      Window.alert(MESSAGES.newerVersionProject());
      return false;
    }

    if (srcYaVersion == 0) {
      // The source file doesn't have a YoungAndroid version number.
      // There are two situations that cause this:
      // 1. The project may have been downloaded from alpha (androidblocks.googlelabs.com) and
      // uploaded to beta (appinventor.googlelabs.com), which is illegal.
      // 2. The project may have been created with beta (appinventor.googlelabs.com) before we
      // started putting version numbers into the source file, which is legal, and nothing
      // really changed between version 0 and version 1.
      //
      // For a limited time, we assume #2, show a warning, and proceed.
      // TODO(lizlooney) - after the limited time is up (when we think that all appinventor
      // projects have been upgraded), we may decide to refuse to load the project.
      Window.alert(MESSAGES.veryOldProject());
    }

    return (srcYaVersion < sysYaVersion);
  }
Пример #5
0
  public PlayerWidget(String url) {
    SimplePanel panel = new SimplePanel(); // create panel to hold the player

    player = null;
    try {
      // create the player, specifing URL of media
      player = new WinMediaPlayer(url, true, "450px", "550px");
      player.showLogger(true);
      panel.setWidget(player); // add player to panel.
    } catch (LoadException e) {
      try {
        player = new QuickTimePlayer(url, true, "450px", "550px");
        panel.setWidget(player); // add player to panel.
        // catch loading exception and alert user
        Window.alert("An error occured while loading");
      } catch (LoadException ep) {
        try {
          player = new FlashMP3Player(url, true, "450px", "550px");
          panel.setWidget(player); // add player to panel.
          // catch loading exception and alert user
          Window.alert("An error occured while loading");
        } catch (LoadException exp) {
          // catch loading exception and alert user
          Window.alert("An error occured while loading");
        } catch (PluginVersionException exp) {
          // required plugin version is not available, alert user possibly providing a link
          // to the plugin download page.
          panel.setWidget(
              new HTML(".. some nice message telling the user to download plugin first .."));
        } catch (PluginNotFoundException exp) {
          // catch PluginNotFoundException and tell user to download plugin, possibly providing
          // a link to the plugin download page.
          panel.setWidget(
              new HTML(".. another nice message telling the user to download plugin.."));
        }
      } catch (PluginVersionException ep) {
        // required plugin version is not available, alert user possibly providing a link
        // to the plugin download page.
        panel.setWidget(
            new HTML(".. some nice message telling the user to download plugin first .."));
      } catch (PluginNotFoundException ep) {
        // catch PluginNotFoundException and tell user to download plugin, possibly providing
        // a link to the plugin download page.
        panel.setWidget(new HTML(".. another nice message telling the user to download plugin.."));
      }

    } catch (PluginVersionException e) {
      // required plugin version is not available, alert user possibly providing a link
      // to the plugin download page.
      panel.setWidget(
          new HTML(".. some nice message telling the user to download plugin first .."));
    } catch (PluginNotFoundException e) {
      // catch PluginNotFoundException and tell user to download plugin, possibly providing
      // a link to the plugin download page.
      panel.setWidget(new HTML(".. another nice message telling the user to download plugin.."));
    }
    initWidget(panel);
  }
Пример #6
0
  private void bindWebGL() {
    // Adds the Surface3D to the document.
    Surface3D surface = new Surface3D(500, 500);
    RootPanel.get().add(surface);
    final GL2 gl = surface.getGL();
    if (gl == null) {
      Window.alert("No WebGL context found. Exiting.");
      return;
    }

    // Sets up the GL context.
    gl.clearColor(0.0f, 0f, 0f, 1f);
    gl.clearDepth(1);
    gl.viewport(0, 0, surface.getWidth(), surface.getHeight());

    gl.enable(EnableCap.DEPTH_TEST);
    gl.depthFunc(DepthFunction.LEQUAL);
    gl.clear(ClearBufferMask.COLOR_BUFFER_BIT, ClearBufferMask.DEPTH_BUFFER_BIT);

    // Creates a lambertian shader.
    LambertianShader shader = new LambertianShader();
    try {
      shader.init(gl);
    } catch (ShaderException e) {
      Window.alert("Error loading the shader.");
      return;
    }

    // Binds the shader.
    shader.bind();

    // Creates a sphere.
    StaticMesh mesh = new StaticMesh(gl, PrimitiveFactory.makeSphere(30, 30));
    mesh.setPositionIndex(shader.getAttributePosition());
    mesh.setNormalIndex(shader.getAttributeNormal());

    shader.setLightPosition(0, 5, 5);
    shader.setDiffuseColor(1, 0, 0, 1);

    // Sets up the model view matrix.
    MatrixStack.MODELVIEW.push();
    MatrixStack.MODELVIEW.translate(0, 0, -5);
    shader.setModelViewMatrix(MatrixStack.MODELVIEW.get());
    MatrixStack.MODELVIEW.pop();

    // Sets up a basic camera for projection.
    MatrixStack.PROJECTION.pushIdentity();
    MatrixStack.PROJECTION.perspective(45, 1, .1f, 100);
    shader.setProjectionMatrix(MatrixStack.PROJECTION.get());
    MatrixStack.PROJECTION.pop();

    // Draws the mesh.
    mesh.draw();

    mesh.dispose();
    shader.dispose();
  }
Пример #7
0
 @Override
 public void onSuccess(String result) {
   if (result == null) {
     Window.alert("添加失败!!!");
   }
   if ("existedExecuteOrder".equals(result)) {
     Window.alert("部分路由工单已经创建过!!!");
   }
 }
        private void checkEvent(ClickEvent eventObject) {
            
            boolean keyMaskPassed = this.clickHandler.checkModifiers(eventObject);
            if (keyMaskPassed) {
                Window.alert("Selected keys are pressed.");
            } else {
                Window.alert("Selected keys don't match!");
            }

        }
Пример #9
0
 @Override
 public void onActionFailure(Throwable caught, String message) {
   if (message != null) {
     Window.alert(message);
   } else {
     Window.alert(caught.getMessage() != null ? caught.getMessage() : caught.toString());
   }
   if (box != null) {
     box.hide();
     box = null;
   }
 }
  private boolean validateFormInput() {

    if (inputNoteTitle.getText().trim().length() == 0) {
      Window.alert("Please enter a title for the new note!");
      inputNoteTitle.setFocus(true);
      return false;
    }
    if (inputNoteText.getText().trim().length() == 0) {
      Window.alert("Please enter a text for the new note!");
      inputNoteText.setFocus(true);
      return false;
    }
    return true;
  }
    private boolean validate(String newFormName) {
      // Check that it meets the formatting requirements.
      if (!TextValidators.isValidIdentifier(newFormName)) {
        Window.alert(MESSAGES.malformedFormNameError());
        return false;
      }

      // Check that it's unique.
      if (otherFormNames.contains(newFormName)) {
        Window.alert(MESSAGES.duplicateFormNameError());
        return false;
      }

      return true;
    }
Пример #12
0
  protected void applyImages(String folderId, String selectedImageId, JSONObject json) {

    JSONObject jsonObj = JSONHelper.getObject(json, "data");

    totalImagesCount = JSONHelper.getInteger(jsonObj, "totalImagesCount");
    prevImageId = JSONHelper.getString(jsonObj, "prevImageId");
    nextImageId = JSONHelper.getString(jsonObj, "nextImageId");
    startIndex = JSONHelper.getPrimitiveInt(jsonObj, "startIndex");

    // parse images
    List<ClientImage> images =
        JSONHelper.getArray(
            jsonObj,
            "images",
            new ValueParser<ClientImage>() {
              @Override
              public ClientImage parse(JSONValue jsonValue) {
                JSONObject json = jsonValue.isObject();
                String id = JSONHelper.getString(json, "id");
                return new ClientImage(id);
              }
            });
    if (GWTUtils.isEmpty(images)) {
      Window.alert("Failed to load images list");
      return;
    }
    loadedImages.clear();
    loadedImages.addAll(images);

    // parse folder
    JSONObject folderJson = JSONHelper.getObject(jsonObj, "folder");
    if (folderJson == null) {
      Window.alert("Failed to get images list!");
      return;
    }
    String folderCaption = JSONHelper.getString(folderJson, "caption");
    long folderSize = JSONHelper.getPrimitiveLong(json, "folderSize");
    int imagesCount = JSONHelper.getPrimitiveInt(json, "imagesCount");
    selectedFolder = new ClientFolder(folderId, folderCaption, null, folderSize, imagesCount);

    if (GWTUtils.isEmpty(selectedImageId)) {
      selectedImageId = loadedImages.get(0).getId();
      History.newItem(folderId + "/" + selectedImageId, false);
    }

    // paint folder, big photo, small images
    showImages(selectedFolder, selectedImageId, images, true);
  }
  protected void performOperation() {
    final String url = GWT.getHostPageBaseURL() + "plugin/reporting/api/cache/clear"; // $NON-NLS-1$
    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, url);
    requestBuilder.setHeader("accept", "text/text");
    requestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
    try {
      requestBuilder.sendRequest(
          null,
          new RequestCallback() {

            public void onError(Request request, Throwable exception) {
              // showError(exception);
            }

            public void onResponseReceived(Request request, Response response) {
              MessageDialogBox dialogBox =
                  new MessageDialogBox(
                      Messages.getString("info"),
                      Messages.getString("reportingDataCacheFlushedSuccessfully"),
                      false,
                      false,
                      true); //$NON-NLS-1$ //$NON-NLS-2$
              dialogBox.center();
            }
          });
    } catch (RequestException e) {
      Window.alert(e.getMessage());
      // showError(e);
    }
  }
Пример #14
0
  public void getAnnotationList(String annotates, final boolean forceDecorate) {
    if (annotates.contains("?")) {
      annotates = annotates.substring(0, annotates.indexOf('?'));
    }
    String url = controller.getAnnoteaServerUrl() + "?w3c_annotates=" + annotates;
    RequestBuilder getRequest = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
    try {
      getRequest.sendRequest(
          null,
          new RequestCallback() {
            public void onError(Request request, Throwable exception) {}

            public void onResponseReceived(Request request, Response response) {
              responseManager.processAnnotationListResponse(response.getText());
              if (forceDecorate) {
                // Force all the annotations to be redecorated
                controller.updateAnnotations(true);
              }
            }
          });
    } catch (RequestException e) {
      GWT.log("Error while requesting annotations: " + url, e);
      Log.debug("Error while requesting annotations: " + url, e);
      Window.alert(e.toString());
    }
  }
Пример #15
0
 public void setVideo(String url) {
   try {
     player.loadMedia(url);
   } catch (LoadException e) {
     Window.alert("An error occured while loading");
   }
 }
Пример #16
0
  /**
   * Ajoute une tache dans la table des tâches. Déclenchée par un click sur le addTaskButton ou par
   * la touche Enter depuis le champ newTaskTextBox.
   */
  private void addTask() {
    String symbol = newTaskTextBox.getText().trim();
    newTaskTextBox.setFocus(true);

    // Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
    if (symbol.length() < 3) {
      Window.alert("le nom de la tâche doit faire plus de 3 caractères.");
      newTaskTextBox.selectAll();
      return;
    }

    newTaskTextBox.setText("");

    // Rename the task if it's already in the table.
    if (tasks.contains(symbol)) {
      int n = 1;
      while (tasks.contains(symbol + " (" + n + ")")) {
        n++;
      }
      symbol = symbol + " (" + n + ")";
    }

    final String finalSymbol = symbol;
    addStock(symbol);
  }
Пример #17
0
  private void delete() {
    final ClientParamSet setToDelete = getSelectedParamSet();
    if (selectionController.getClientParamSets().size() <= 1) {
      Window.alert("Cannot delete all parameter sets - at least one must remain.");
    } else {
      if (Window.confirm(
          "Do you really want to delete parameter set " + setToDelete.getName() + "?")) {
        serviceAsync.delete(
            new Service.Token(true),
            selector.getSelectedParamSet(),
            new AsyncCallback<Void>() {
              public void onFailure(Throwable throwable) {
                handleGlobalError(throwable);
              }

              public void onSuccess(Void aVoid) {
                selectionController.refresh(
                    new ParamSetSelectionController.Callback() {
                      public void refreshed() {
                        final List<ClientParamSet> paramSets =
                            selectionController.getClientParamSets();
                        selectionController.select(paramSets.get(0));
                      }
                    });
              }
            });
      }
    }
  }
Пример #18
0
  public void deleteFolder(final FileNode object) {
    String filename = getCanonicalName(object);

    String url = this.repo.getUri() + "/folder?filename=" + URL.encodeQueryString(filename);
    // Send request to server and catch any errors.
    RequestBuilder builder = AuthenticatedRequestFactory.newRequest(RequestBuilder.DELETE, url);
    try {
      Request request =
          builder.sendRequest(
              null,
              new RequestCallback() {
                public void onError(Request request, Throwable exception) {
                  // displayError("Couldn't retrieve JSON "+exception.getMessage());
                }

                public void onResponseReceived(Request request, Response response) {
                  GWT.log(response.getStatusCode() + " " + response.getText());
                  if (200 != response.getStatusCode()) {
                    Window.alert(
                        "Delete failure: " + response.getStatusText() + " " + response.getText());
                  }
                }
              });
    } catch (RequestException e) {
      Window.alert("Delete exception: " + e.toString());
    }
  }
Пример #19
0
  @Override
  public void saveClicked() {
    LOGGER.log(Level.FINE, "Attempting save of Person.");

    final PersonDriver personDriver = this.personEditView.getPersonDriver();
    RequestContext context = personDriver.flush();

    if (personDriver.hasErrors()) {
      Window.alert("ERRORS");
      return;
    }

    context.fire(
        new Receiver<Void>() {
          @Override
          public void onSuccess(Void arg0) {
            LOGGER.log(Level.FINE, "Person save successful.");
            placeController.goTo(PersonPlace.list());
          }

          @Override
          public void onFailure(ServerFailure error) {
            LOGGER.log(Level.WARNING, "Person save failed. " + error.getMessage());
            Window.alert("FAILURE\n\n" + error.getMessage());
          }

          @Override
          public void onViolation(Set<Violation> errors) {
            LOGGER.log(Level.FINE, "Person save failed. Violation errors present.");
            personDriver.setViolations(errors);
          }
        });
  }
Пример #20
0
  @UiHandler("buttonBuy")
  public void acceptBuy(ClickEvent e) {

    // RootPanel.get("page2");
    Window.alert(
        "Le système de paiement est actuellement en maintenance, merci de votre compréhension.");

    List<Reservation> l = new ArrayList<Reservation>();
    for (Offre o : listOffers.getList()) {
      Reservation r = new Reservation();
      r.setIdOffre(o.getId());
      r.setIdUtilisateur(4);

      l.add(r);
    }

    service.doReservation(
        "",
        l,
        "09090909090",
        new AsyncCallback<Void>() {

          @Override
          public void onFailure(Throwable caught) {

            // TODO Auto-generated method stub

          }

          @Override
          public void onSuccess(Void result) {}
        });
  }
  private void caricaTabellaDati() {

    try {
      if (smplcmbxSede.isValid()) {
        String sede = smplcmbxSede.getRawValue().toString();

        AdministrationService.Util.getInstance()
            .getRiepilogoDatiCostiPersonale(
                sede,
                new AsyncCallback<List<RiepilogoCostiDipendentiModel>>() {
                  @Override
                  public void onSuccess(List<RiepilogoCostiDipendentiModel> result) {
                    if (result == null)
                      Window.alert("Impossibile accedere ai dati sui costi dipendenti!");
                    else loadTable(result);
                  }

                  @Override
                  public void onFailure(Throwable caught) {
                    Window.alert("Errore connessione on getRiepilogoDatiCostiPersonale();");
                    caught.printStackTrace();
                  }
                });
      }
    } catch (Exception e) {
      e.printStackTrace();
      Window.alert("Problemi durante il caricamento dei dati sui costi personale.");
    }
  }
Пример #22
0
  private static List<Invoice> parser(String text) {
    JsArray<InvoiceJavaScript> modulosJS = InvoiceJavaScript.eval(text);
    List<Invoice> invoices = new ArrayList<Invoice>();

    for (int i = 0, j = modulosJS.length(); i < j; i++) {
      InvoiceJavaScript invoiceJavaScript = modulosJS.get(i);
      Invoice invoice = new Invoice();
      invoice.setCode(invoiceJavaScript.getCode());
      invoice.setContractId(invoiceJavaScript.getContractId());
      invoice.setContractName(invoiceJavaScript.getContractName());
      invoice.setId(invoiceJavaScript.getId());
      invoice.setInvoiceStatusId(invoiceJavaScript.getInvoiceStatusId());
      invoice.setInvoiceStatusName(invoiceJavaScript.getInvoiceStatusName());
      invoice.setClientId(invoiceJavaScript.getClientId());
      invoice.setClientName(invoiceJavaScript.getClientName());
      invoice.setAmount(invoiceJavaScript.getAmount());

      try {
        invoice.setDate(invoiceJavaScript.getDate());
      } catch (IllegalValueException e) {
        Window.alert("Error con las fechas de contrato: " + e.getMessage());
      }
      invoices.add(invoice);
    }

    return invoices;
  }
 @Override
 protected boolean okAction() {
   if (automaticRadioButton.isChecked()) {
     property.setValue(CONST_AUTOMATIC);
   } else if (fillParentRadioButton.isChecked()) {
     property.setValue(CONST_FILL_PARENT);
   } else {
     // Custom length
     String text = customLengthField.getText();
     // Make sure it's a non-negative number.  It is important
     // that this check stay within the custom length case because
     // CONST_AUTOMATIC and CONST_FILL_PARENT are deliberately negative.
     boolean success = false;
     try {
       if (Integer.parseInt(text) >= 0) {
         success = true;
       }
     } catch (NumberFormatException e) {
       // fall through with success == false
     }
     if (!success) {
       Window.alert(MESSAGES.nonnumericInputError());
       return false;
     }
     property.setValue(text);
   }
   return true;
 }
Пример #24
0
  private void calculateHoursInclTravel() {

    try {
      int mgmtHours = Integer.parseInt(display.getMgmtHours().getText().toString());

      int workManHours = Integer.parseInt(display.getFieldWorkManHours().getText().toString());

      //		Total Working Man Hours = Field Work Man Hours + mgmt hrs
      display.getTotalWorkingManHours().setText(String.valueOf((mgmtHours + workManHours)));

      int travelDays =
          Integer.parseInt(
              display
                  .getTravelingDaysListBox()
                  .getItemText(display.getTravelingDaysListBox().getSelectedIndex()));

      // Hours inclusive of travel = Total working man hours + travelling days*8

      display
          .getHoursInclusiveOfTravel()
          .setText(String.valueOf(mgmtHours + workManHours + travelDays * 8));
    } catch (Exception e) {
      Window.alert("Please enter only numbers in numeric fields");
    }
  }
    private void caricaFieldSet(List<IntervalliCommesseModel> result) {
      String descrizioneCompleta = new String();
      List<IntervalliCommesseModel> lista = new ArrayList<IntervalliCommesseModel>();
      Collections.sort(
          result,
          new Comparator<IntervalliCommesseModel>() {
            public int compare(IntervalliCommesseModel s1, IntervalliCommesseModel s2) {
              return s1.getNumeroCommessa().compareToIgnoreCase(s2.getNumeroCommessa());
            }
          });

      lista.addAll(result);

      int size;
      size = lista.size();

      if (size < 0) {

        Window.alert("error: Impossibile accedere alla tabella AssociazioniDipendente;");

      } else {

        if (size == 0) {
          txtNoCommesse.setText("Nessuna Commessa Associata!");
          txtNoCommesse.setVisible(true);

        } else {
          removeAll();

          for (int i = 0; i < size; i++) {
            String num = String.valueOf(i);

            frmInsCommesse = new FormInserimentoIntervalloCommessa("2");
            frmInsCommesse.setItemId(num);

            // frmInsCommesse.txtfldNumeroCommessa.setValue(result.get(i).getNumeroCommessa());
            frmInsCommesse.txtfldOreIntervallo.setValue(result.get(i).getOreLavoro());
            frmInsCommesse.txtfldOreViaggio.setValue(result.get(i).getOreViaggio());
            frmInsCommesse.txtOreTotLavoro.setText(
                "Totale nel Mese: " + result.get(i).getTotOreLavoro());
            frmInsCommesse.txtOreTotViaggio.setText(
                "Totale nel Mese: " + result.get(i).getTotOreViaggio());

            descrizioneCompleta =
                result.get(i).getNumeroCommessa()
                    + " ("
                    + result.get(i).getDescrizione().toLowerCase()
                    + ") ";

            // frmInsCommesse.txtDescrizione.setText(result.get(i).getDescrizione().toLowerCase());
            frmInsCommesse.txtDescrizione.setText(descrizioneCompleta);

            add(frmInsCommesse);
          }
        }

        add(buttonBar);
        layout();
      }
    }
Пример #26
0
  /** @param node */
  public void makePublic(final FileNode node, boolean isPublic) {
    String url = node.getRepository() + "/permissions";
    RequestBuilder builder = AuthenticatedRequestFactory.newRequest(RequestBuilder.POST, url);
    builder.setHeader("Content-type", "application/x-www-form-urlencoded");
    StringBuilder args = new StringBuilder();
    args.append("isPublic=");
    args.append(URL.encodeQueryString(Boolean.toString(isPublic)));
    args.append("&filename=");
    args.append(URL.encodeQueryString(getCanonicalName(node)));
    try {
      Request request =
          builder.sendRequest(
              args.toString(),
              new RequestCallback() {
                public void onError(Request request, Throwable exception) {
                  // displayError("Couldn't retrieve JSON "+exception.getMessage());
                }

                public void onResponseReceived(Request request, Response response) {
                  GWT.log("Got reply");
                  if (200 == response.getStatusCode()) {
                    GWT.log("Reply is" + response.getText());
                    GWT.log("Headers is " + response.getHeadersAsString());
                    GWT.log("Status Text " + response.getStatusText());
                    fetchFiles(repositoryUri, node.getPath());
                  } else {
                    Window.alert(
                        "Update failure: " + response.getStatusText() + " " + response.getText());
                  }
                }
              });
    } catch (RequestException e) {
      Window.alert("Update exception: " + e.toString());
    }
  }
Пример #27
0
  public void getRepo(String repoUri) {
    // Send request to server and catch any errors.
    this.lastRepoURI = repoUri;
    // this.lastPrefix = null;
    RequestBuilder builder = AuthenticatedRequestFactory.newRequest(RequestBuilder.GET, repoUri);
    try {
      Request request =
          builder.sendRequest(
              null,
              new RequestCallback() {
                public void onError(Request request, Throwable exception) {
                  // displayError("Couldn't retrieve JSON "+exception.getMessage());
                }

                public void onResponseReceived(Request request, Response response) {
                  GWT.log(response.getStatusCode() + " " + response.getText());
                  if (200 == response.getStatusCode()) {
                    Repository repo = Repository.asRepository(response.getText());
                    updateRepo(repo);
                  } else {
                    Window.alert(
                        "Update failure: " + response.getStatusText() + " " + response.getText());
                  }
                }
              });
    } catch (RequestException e) {
      Window.alert("Update exception: " + e.toString());
    }
  }
Пример #28
0
  public boolean creatBarPloterPDF(String username, String fileName, String theData) {

    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, "FileSavePlotServlet");
    StringBuffer postData = new StringBuffer();

    postData.append(URL.encode("username")).append("=").append(URL.encode(username));
    postData.append(URL.encode("&"));
    postData.append(URL.encode("plotFileName")).append("=").append(URL.encode(fileName));
    postData.append(URL.encode("&"));
    postData.append(URL.encode("theData")).append("=").append(URL.encode(theData));

    builder.setHeader("Content-type", "application/x-www-form-urlencoded");

    try {
      builder.setRequestData(postData.toString()); /* or other RequestCallback impl*/

      builder.setCallback(this);

      com.google.gwt.http.client.Request res = builder.send();

    } catch (Exception e) {
      // handle this
      Window.alert("Exception..." + e.getMessage());
    }
    return true;
  }
  private void submitMatch() {
    Match m =
        new Match(
            league.getId(),
            new Date(),
            league.getSports().get(sportBox.getSelectedIndex()),
            league.getPlayers().get(player1Box.getSelectedIndex() - 1),
            league.getPlayers().get(player2Box.getSelectedIndex() - 1));
    for (int i = 0; i < player1Score.size(); i++) {
      try {
        if (!player1Score.get(i).getText().equals("")
            && !player2Score.get(i).getText().equals("")) {
          m.addSet(
              new Set(
                  m.getSport(),
                  Integer.parseInt(player1Score.get(i).getText()),
                  Integer.parseInt(player2Score.get(i).getText())));
        }
      } catch (NumberFormatException e) {
        Window.alert("Failed to parse number: " + e.getMessage());
      }
    }
    AsyncCallback<Void> callback =
        new AsyncCallback<Void>() {
          public void onFailure(Throwable caught) {
            Window.alert("Failed to save match.");
          }

          public void onSuccess(Void arg) {
            Spelstegen.showMessage("Match sparad.", false);
            resetPanel();
          }
        };
    ServiceManager.getInstance().saveMatch(m, loggedInPlayer, league, callback);
  }
Пример #30
0
    @Override
    public void onResponseReceived(Request request, Response response) {
      JSONValue j = JSONParser.parseStrict(response.getText());
      JSONObject obj = j.isObject();
      if (obj != null && obj.containsKey("error")) {
        Window.alert(obj.get("error").isString().stringValue());
        changeButtonSelection();
        setTextEnabled(false);
        clearTextBoxes();
        singleSelectionModel.clear();
      } else {
        List<OrganismInfo> organismInfoList =
            OrganismInfoConverter.convertJSONStringToOrganismInfoList(response.getText());
        dataGrid.setSelectionModel(singleSelectionModel);
        MainPanel.getInstance().getOrganismInfoList().clear();
        MainPanel.getInstance().getOrganismInfoList().addAll(organismInfoList);
        changeButtonSelection();
        OrganismChangeEvent organismChangeEvent = new OrganismChangeEvent(organismInfoList);
        organismChangeEvent.setAction(OrganismChangeEvent.Action.LOADED_ORGANISMS);
        Annotator.eventBus.fireEvent(organismChangeEvent);

        // in the case where we just add one . . .we should refresh the app state
        if (organismInfoList.size() == 1) {
          MainPanel.getInstance().getAppState();
        }
      }
      if (savingNewOrganism) {
        savingNewOrganism = false;
        setNoSelection();
        changeButtonSelection(false);
        loadingDialog.hide();
      }
    }