public static void performLogin(final AsyncCallback<Boolean> callback) {
    // let's only login if we are not actually logged in
    try {
      final String url = GWT.getHostPageBaseURL() + "api/mantle/isAuthenticated"; // $NON-NLS-1$
      RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url);
      requestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
      requestBuilder.setHeader("accept", "text/plain");
      requestBuilder.sendRequest(
          null,
          new RequestCallback() {

            public void onError(Request request, Throwable caught) {
              MantleLoginDialog dialog = new MantleLoginDialog(callback, false);
              dialog.show();
            }

            public void onResponseReceived(Request request, Response response) {
              if (!"true".equalsIgnoreCase(response.getText())) {
                MantleLoginDialog dialog = new MantleLoginDialog(callback, false);
                dialog.show();
              }
            }
          });
    } catch (RequestException e) {
      MantleLoginDialog dialog = new MantleLoginDialog(callback, false);
      dialog.show();
    }
  }
  public void saveUser(final String name, final String password) {
    String serviceUrl = GWT.getHostPageBaseURL() + "api/userroledao/createUser";
    RequestBuilder executableTypesRequestBuilder =
        new RequestBuilder(RequestBuilder.PUT, serviceUrl);
    try {
      executableTypesRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
      executableTypesRequestBuilder.setHeader("Content-Type", "application/json");
      String json =
          "{\"userName\": \""
              + encodeUri(name)
              + "\", \"password\": \""
              + encodeUri(password)
              + "\"}";
      executableTypesRequestBuilder.sendRequest(
          json,
          new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              displayErrorInMessageBox(
                  Messages.getString("Error"), exception.getLocalizedMessage());
            }

            public void onResponseReceived(Request request, Response response) {
              initializeAvailableUsers(name);
              initializeRoles(
                  rolesListBox.getValue(rolesListBox.getSelectedIndex()),
                  "api/userroledao/roles",
                  rolesListBox);
            }
          });
    } catch (RequestException e) {
      displayErrorInMessageBox(Messages.getString("Error"), e.getLocalizedMessage());
    }
  }
  public void activate() {
    processLDAPmode();
    initializeActionBaseSecurityElements();
    initializeAvailableUsers(null);

    final String url = GWT.getHostPageBaseURL() + "api/system/authentication-provider";
    RequestBuilder executableTypesRequestBuilder = new RequestBuilder(RequestBuilder.GET, url);
    executableTypesRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
    executableTypesRequestBuilder.setHeader("accept", "application/json");
    try {
      executableTypesRequestBuilder.sendRequest(
          null,
          new RequestCallback() {

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

            public void onResponseReceived(Request request, Response response) {
              boolean usingLDAP = response.getText().contains("ldap");
              if (usingLDAP) {
                initializeRoles(null, "api/userrolelist/roles", rolesListBox);
              } else {
                initializeRoles(null, "api/userroledao/roles", rolesListBox);
              }
              initializeRoles(null, "api/userrolelist/extraRoles", systemRolesListBox);
            }
          });
    } catch (RequestException e) {
      // ignored
    }
  }
  private void processLDAPmode() {
    final String url = GWT.getHostPageBaseURL() + "api/system/authentication-provider";
    RequestBuilder executableTypesRequestBuilder = new RequestBuilder(RequestBuilder.GET, url);
    executableTypesRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
    executableTypesRequestBuilder.setHeader("accept", "application/json");
    try {
      executableTypesRequestBuilder.sendRequest(
          null,
          new RequestCallback() {

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

            public void onResponseReceived(Request request, Response response) {
              boolean usingLDAP = !response.getText().contains("ldap");
              usersLabelPanel.setVisible(usingLDAP);
              usersPanel.setVisible(usingLDAP);
              newRoleButton.setVisible(usingLDAP);
              deleteRoleButton.setVisible(usingLDAP);

              if (!usingLDAP) {
                mainTabPanel.getTab(0).setVisible(false);
                mainTabPanel.selectTab(1);
              } else {
                mainTabPanel.getTab(0).setVisible(true);
                mainTabPanel.selectTab(0);
              }
            }
          });
    } catch (RequestException e) {
      // ignored
    }
  }
  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);
    }
  }
  protected boolean addBlockoutPeriod(
      final JSONObject schedule, final JsJobTrigger trigger, String urlSuffix) {
    String url = GWT.getHostPageBaseURL() + "api/scheduler/blockout/" + urlSuffix; // $NON-NLS-1$

    RequestBuilder addBlockoutPeriodRequest = new RequestBuilder(RequestBuilder.POST, url);
    addBlockoutPeriodRequest.setHeader("accept", "text/plain"); // $NON-NLS-1$ //$NON-NLS-2$
    addBlockoutPeriodRequest.setHeader(
        "Content-Type", "application/json"); // $NON-NLS-1$ //$NON-NLS-2$
    addBlockoutPeriodRequest.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");

    // Create a unique blockout period name
    final Long duration = trigger.getBlockDuration();
    final String blockoutPeriodName =
        trigger.getScheduleType()
            + Random.nextInt()
            + ":"
            + //$NON-NLS-1$
            /* PentahoSessionHolder.getSession().getName() */ "admin"
            + ":"
            + duration; //$NON-NLS-1$ //$NON-NLS-2$

    // Add blockout specific parameters
    JSONObject addBlockoutParams = schedule;
    addBlockoutParams.put("jobName", new JSONString(blockoutPeriodName)); // $NON-NLS-1$
    addBlockoutParams.put("duration", new JSONNumber(duration)); // $NON-NLS-1$
    addBlockoutParams.put("timeZone", new JSONString(scheduleEditorWizardPanel.getTimeZone()));

    try {
      addBlockoutPeriodRequest.sendRequest(
          addBlockoutParams.toString(),
          new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              MessageDialogBox dialogBox =
                  new MessageDialogBox(
                      Messages.getString("error"),
                      exception.toString(),
                      false,
                      false,
                      true); //$NON-NLS-1$
              dialogBox.center();
              setDone(false);
            }

            public void onResponseReceived(Request request, Response response) {
              if (response.getStatusCode() == Response.SC_OK) {
                if (null != callback) {
                  callback.okPressed();
                }
              }
            }
          });
    } catch (RequestException e) {
      // ignored
    }

    return true;
  }
  private void getUsersInRole(String role) {
    final String url =
        GWT.getHostPageBaseURL() + "api/userroledao/roleMembers?roleName=" + encodeUri(role);
    RequestBuilder executableTypesRequestBuilder = new RequestBuilder(RequestBuilder.GET, url);
    executableTypesRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
    executableTypesRequestBuilder.setHeader("accept", "application/xml");
    try {
      executableTypesRequestBuilder.sendRequest(
          null,
          new RequestCallback() {

            public void onError(Request request, Throwable exception) {
              displayErrorInMessageBox(
                  Messages.getString("Error"), exception.getLocalizedMessage());
            }

            public void onResponseReceived(Request request, Response response) {
              selectedMembersListBox.clear();
              String txt = response.getText();
              Document doc = XMLParser.parse(txt);
              NodeList users = doc.getElementsByTagName("users");
              for (int i = 0; i < users.getLength(); i++) {
                Node userNode = users.item(i);
                String user = userNode.getFirstChild().getNodeValue();
                selectedMembersListBox.addItem(user);
              }

              Timer t =
                  new Timer() {
                    public void run() {
                      if (usersListBox.getItemCount() > 0) {
                        cancel();
                        // availableMembersListBox = usersListBox - selectedMembersListBox
                        availableMembersListBox.clear();
                        for (int i = 0; i < usersListBox.getItemCount(); i++) {
                          String user = usersListBox.getValue(i);
                          boolean isSelected = false;
                          for (int j = 0; j < selectedMembersListBox.getItemCount(); j++) {
                            if (selectedMembersListBox.getValue(j).equals(user)) {
                              isSelected = true;
                            }
                          }
                          if (!isSelected) {
                            availableMembersListBox.addItem(user);
                          }
                        }
                      }
                    }
                  };
              t.scheduleRepeating(100);
            }
          });
    } catch (RequestException e) {
      displayErrorInMessageBox(Messages.getString("Error"), e.getLocalizedMessage());
    }
  }
示例#8
0
 private RequestBuilder postRequestBuilder() {
   // lazy init, because endpointConfig.getUrl() is not initialized at construction time
   if (prb == null) {
     prb = new RequestBuilder(RequestBuilder.POST, endpointConfig.getUrl());
     prb.setHeader(HEADER_ACCEPT, DMR_ENCODED);
     prb.setHeader(HEADER_CONTENT_TYPE, DMR_ENCODED);
     prb.setIncludeCredentials(true);
   }
   return prb;
 }
  /**
   * Before creating a new schedule, we want to check to see if the schedule that is being created
   * is going to conflict with any one of the blockout periods if one is provisioned.
   *
   * @param schedule
   * @param trigger
   */
  protected void verifyBlockoutConflict(final JSONObject schedule, final JsJobTrigger trigger) {
    String url = GWT.getHostPageBaseURL() + "api/scheduler/blockout/blockstatus"; // $NON-NLS-1$

    RequestBuilder blockoutConflictRequest = new RequestBuilder(RequestBuilder.POST, url);
    blockoutConflictRequest.setHeader("accept", "application/json"); // $NON-NLS-1$ //$NON-NLS-2$
    blockoutConflictRequest.setHeader(
        "Content-Type", "application/json"); // $NON-NLS-1$ //$NON-NLS-2$
    blockoutConflictRequest.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");

    final JSONObject verifyBlockoutParams = schedule;
    verifyBlockoutParams.put("jobName", new JSONString(scheduleName)); // $NON-NLS-1$

    try {
      blockoutConflictRequest.sendRequest(
          verifyBlockoutParams.toString(),
          new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              MessageDialogBox dialogBox =
                  new MessageDialogBox(
                      Messages.getString("error"),
                      exception.toString(),
                      false,
                      false,
                      true); //$NON-NLS-1$
              dialogBox.center();
              setDone(false);
            }

            public void onResponseReceived(Request request, Response response) {
              if (response.getStatusCode() == Response.SC_OK) {
                JsBlockStatus statusResponse =
                    (JsBlockStatus) parseJson(JsonUtils.escapeJsonForEval(response.getText()));

                // Determine if this schedule conflicts all the time or some of the time
                boolean partiallyBlocked =
                    Boolean.parseBoolean(statusResponse.getPartiallyBlocked());
                boolean totallyBlocked = Boolean.parseBoolean(statusResponse.getTotallyBlocked());
                if (partiallyBlocked || totallyBlocked) {
                  promptDueToBlockoutConflicts(totallyBlocked, partiallyBlocked, schedule, trigger);
                } else {
                  // Continue with other panels in the wizard (params, email)
                  handleWizardPanels(schedule, trigger);
                }
              } else {
                handleWizardPanels(schedule, trigger);
              }
            }
          });
    } catch (RequestException e) {
      // ignored
    }

    super.nextClicked();
  }
  private void populateTimeZonePicker() {

    String url = GWT.getHostPageBaseURL() + "api/system/timezones"; // $NON-NLS-1$
    RequestBuilder timeZonesRequest = new RequestBuilder(RequestBuilder.GET, url);
    timeZonesRequest.setHeader("accept", "application/json"); // $NON-NLS-1$ //$NON-NLS-2$
    timeZonesRequest.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
    try {
      timeZonesRequest.sendRequest(
          null,
          new RequestCallback() {

            @Override
            public void onResponseReceived(Request request, Response response) {
              timeZonePicker.clear();
              String responseText = response.getText();
              JSONValue value = JSONParser.parseLenient(responseText);
              JSONObject object = value.isObject();
              value = object.get("timeZones");
              JSONValue serverTZvalue = object.get("serverTzId");
              JSONString serverTZIdString = serverTZvalue.isString();
              String serverTZId = serverTZIdString.stringValue();
              object = value.isObject();
              value = object.get("entry");
              JSONArray timeZonesJSONArray = value.isArray();
              for (int i = 0; i < timeZonesJSONArray.size(); i++) {
                JSONValue entryValue = timeZonesJSONArray.get(i);
                JSONObject entryObject = entryValue.isObject();
                JSONValue keyValue = entryObject.get("key");
                JSONValue theValue = entryObject.get("value");
                String key = keyValue.isString().stringValue();
                String valueForKey = theValue.isString().stringValue();
                timeZonePicker.addItem(valueForKey, key);
              }
              for (int i = 0; i < timeZonePicker.getItemCount(); i++) {
                if (timeZonePicker.getValue(i).equalsIgnoreCase(serverTZId)) {
                  timeZonePicker.setSelectedIndex(i);
                  break;
                }
              }
            }

            @Override
            public void onError(Request request, Throwable exception) {
              // TODO Auto-generated method stub

            }
          });
    } catch (RequestException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 public static RequestBuilder newCacheManagerRequest(Method httpMethod, String url) {
   if (!authenticated) {
     GWT.log("Attempts to build a request when no credentials present");
     return null;
   }
   RequestBuilder request = new RequestBuilder(httpMethod, url);
   request.setTimeoutMillis(35000);
   request.setHeader("Authorization", base64);
   request.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
   // request.setUser(defaultUsername);
   // request.setPassword(defaultPassword);
   return request;
 }
  public void deleteRoles() {

    String selectedRoles = "";
    for (int i = 0; i < rolesListBox.getItemCount(); i++) {
      if (rolesListBox.isItemSelected(i)) {
        selectedRoles = selectedRoles + encodeUri(rolesListBox.getValue(i)) + "|";
      }
    }

    String serviceUrl =
        GWT.getHostPageBaseURL() + "api/userroledao/deleteRoles?roleNames=" + selectedRoles;
    RequestBuilder executableTypesRequestBuilder =
        new RequestBuilder(RequestBuilder.PUT, serviceUrl);
    try {
      executableTypesRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
      executableTypesRequestBuilder.sendRequest(
          null,
          new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              displayErrorInMessageBox(
                  Messages.getString("Error"), exception.getLocalizedMessage());
            }

            public void onResponseReceived(Request request, Response response) {
              checkForError(Messages.getString("Error"), response);
              availableMembersListBox.clear();
              selectedMembersListBox.clear();
              initializeRoles(null, "api/userroledao/roles", rolesListBox);
              initializeAvailableUsers(usersListBox.getValue(usersListBox.getSelectedIndex()));
            }
          });
    } catch (RequestException e) {
      displayErrorInMessageBox(Messages.getString("Error"), e.getLocalizedMessage());
    }
  }
  private void initializeSystemRoles() {
    final String url = GWT.getHostPageBaseURL() + "api/userrole/systemRoles"; // $NON-NLS-1$
    RequestBuilder executableTypesRequestBuilder = new RequestBuilder(RequestBuilder.GET, url);
    executableTypesRequestBuilder.setHeader("accept", "application/json");
    try {
      executableTypesRequestBuilder.sendRequest(
          null,
          new RequestCallback() {

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

            public void onResponseReceived(Request request, Response response) {
              if (response.getStatusCode() == Response.SC_OK) {

                JsUserRoleList roleList =
                    (JsUserRoleList) parseRoleList(JsonUtils.escapeJsonForEval(response.getText()));
                JsArrayString jsRoleNames = roleList.getRoles();
                for (int i = 0; i < jsRoleNames.length(); i++) {
                  systemRoles.add(jsRoleNames.get(i));
                }
                Collections.sort(systemRoles);
              } else {
              }
            }
          });
    } catch (RequestException e) {
    }
  }
示例#14
0
  private void postyRequest(String url, String data) {
    final RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, url);
    rb.setHeader("Content-type", "application/x-www-form-urlencoded");
    try {
      rb.sendRequest(
          data,
          new RequestCallback() {
            public void onError(final Request request, final Throwable exception) {
              Window.alert(exception.getMessage());
            }

            public void onResponseReceived(final Request request, final Response response) {
              // Window.alert(response.getText());
              int id = Integer.parseInt(response.getText());
              if (id == 1) {
                String url = "http://localhost:3000/workers.json";
                getRequest(url);
              } else if (id > 1) {
                Frame frame = new Frame("http://localhost:3000/workshops/summary");
                RootPanel.get().add(frame);
                mainPanel.clear();
                mainPanel.add(frame);
                // Window.alert("" + id);
              } else {
                userBox.setText("");
                passBox.setText("");
              }
            }
          });
    } catch (final Exception e) {
      Window.alert(e.getMessage());
    }
  }
示例#15
0
  public static void retrieveAncestors(final Event event, final PathHandler handler) {
    String url = "/ReactomeRESTfulAPI/RESTfulWS/queryEventAncestors/" + event.getDbId();
    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url);
    requestBuilder.setHeader("Accept", "application/json");
    try {
      requestBuilder.sendRequest(
          null,
          new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
              try {
                JSONArray list = JSONParser.parseStrict(response.getText()).isArray();
                Ancestors ancestors = new Ancestors(list);
                List<Path> paths =
                    getPathsWithoutOrphanPathways(ancestors.getPathsContaining(event));
                handler.onPathsRetrieved(paths);
              } catch (Exception ex) {
                // ToDo: Look into new Error Handling
              }
            }

            @Override
            public void onError(Request request, Throwable exception) {
              // ToDo: Look into new Error Handling
            }
          });
    } catch (RequestException ex) {
      // ToDo: Look into new Error Handling
    }
  }
示例#16
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;
  }
  protected void initializeExecutableFileTypes() {
    final String moduleBaseURL = GWT.getModuleBaseURL();
    final String moduleName = GWT.getModuleName();
    final String contextURL = moduleBaseURL.substring(0, moduleBaseURL.lastIndexOf(moduleName));
    final String url = contextURL + "api/repos/executableTypes"; // $NON-NLS-1$
    RequestBuilder executableTypesRequestBuilder = new RequestBuilder(RequestBuilder.GET, url);
    executableTypesRequestBuilder.setHeader("accept", "application/json");
    try {
      executableTypesRequestBuilder.sendRequest(
          null,
          new RequestCallback() {

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

            public void onResponseReceived(Request request, Response response) {
              if (response.getStatusCode() == Response.SC_OK) {
                JSONObject jsonObject = (JSONObject) JSONParser.parse(response.getText());
                JSONArray jsonList = (JSONArray) jsonObject.get("executableFileTypeDto");
                for (int i = 0; i < jsonList.size(); i++) {
                  JSONObject executableType = (JSONObject) jsonList.get(i);
                  executableFileExtensions.add(
                      executableType.get("extension").isString().stringValue());
                }
              } else {
                // showServerError(response);
              }
            }
          });
    } catch (RequestException e) {
      // showError(e);
    }
  }
示例#18
0
  private RequestBuilder buildRequest(RequestBuilder.Method httpMethod) {
    String resourceId = idField.getText();
    String resourceUrl = "/resources/customers/";

    if (httpMethod != RequestBuilder.POST) {
      resourceUrl += URL.encode(resourceId);
    }
    RequestBuilder request = new RequestBuilder(httpMethod, resourceUrl);
    if (httpMethod == RequestBuilder.PUT || httpMethod == RequestBuilder.POST) {
      if (resourceId.equals("")) {
        resourceId = "0";
      }
      request.setRequestData(
          "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><customer id=\""
              + resourceId
              + "\"><fullname>"
              + nameField.getText()
              + "</fullname>"
              + "<address><street>"
              + streetField.getText()
              + "</street><city>"
              + cityField.getText()
              + "</city><state>"
              + stateField.getText()
              + "</state><zip>"
              + zipField.getText()
              + "</zip></address></customer>");
      request.setHeader("Content-Type", "application/xml; charset=utf-8");
    }
    return request;
  }
  /*
   * This method is currently not called by the RPC framework.  When it is, we can remove the sessionId
   * logic from the GWTServiceLookup class.
   *
   * For background information, please see http://code.google.com/p/google-web-toolkit/issues/detail?id=5668
   */
  @Override
  protected <T> RequestBuilder doPrepareRequestBuilder(
      ResponseReader responseReader,
      String methodName,
      RpcStatsContext statsContext,
      String requestData,
      AsyncCallback<T> callback) {

    RequestBuilder rb =
        super.doPrepareRequestBuilder(
            responseReader, methodName, statsContext, requestData, callback);

    String sessionId = UserSessionManager.getSessionId();
    if (sessionId != null) {
      if (Log.isDebugEnabled()) {
        Log.debug(
            "SessionRpcRequestBuilder is adding sessionId to request for (" + methodName + ")");
      }
      rb.setHeader(UserSessionManager.SESSION_NAME, sessionId);
    } else {
      Log.error("SessionRpcRequestBuilder missing sessionId for request (" + methodName + ")");
    }

    return rb;
  }
  /** @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());
    }
  }
  private void modifyUserRoles(final String userName, String serviceUrl) {
    RequestBuilder executableTypesRequestBuilder =
        new RequestBuilder(RequestBuilder.PUT, serviceUrl);
    try {
      executableTypesRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
      executableTypesRequestBuilder.sendRequest(
          null,
          new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              displayErrorInMessageBox(
                  Messages.getString("Error"), exception.getLocalizedMessage());
            }

            public void onResponseReceived(Request request, Response response) {
              checkForError(Messages.getString("Error"), response);
              getRolesForUser(userName);
              initializeRoles(
                  rolesListBox.getValue(rolesListBox.getSelectedIndex()),
                  "api/userroledao/roles",
                  rolesListBox);
            }
          });
    } catch (RequestException e) {
      displayErrorInMessageBox(Messages.getString("Error"), e.getLocalizedMessage());
    }
  }
示例#22
0
 public Method headers(Map<String, String> headers) {
   if (headers != null) {
     for (Entry<String, String> entry : headers.entrySet()) {
       builder.setHeader(entry.getKey(), entry.getValue());
     }
   }
   return this;
 }
  private void initializeLogicalRoleMappings() {
    final String url = GWT.getHostPageBaseURL() + "api/userrole/logicalRoleMap"; // $NON-NLS-1$
    RequestBuilder executableTypesRequestBuilder = new RequestBuilder(RequestBuilder.GET, url);
    executableTypesRequestBuilder.setHeader("accept", "application/json");
    try {
      executableTypesRequestBuilder.sendRequest(
          null,
          new RequestCallback() {

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

            public void onResponseReceived(Request request, Response response) {
              if (response.getStatusCode() == Response.SC_OK) {
                JsLogicalRoleMap logicalRoleMap =
                    (JsLogicalRoleMap)
                        parseRoleMappings(JsonUtils.escapeJsonForEval(response.getText()));
                if (logicalRoles.size() == 0) {
                  for (int i = 0; i < logicalRoleMap.getLogicalRoles().length(); i++) {

                    CheckBox permCB =
                        new CheckBox(logicalRoleMap.getLogicalRoles().get(i).getLocalizedName());
                    permCB.addValueChangeHandler(SecurityPanel.this);
                    permissionPanel.add(permCB);
                    logicalRoles.put(
                        logicalRoleMap.getLogicalRoles().get(i).getLocalizedName(),
                        new LogicalRoleInfo(
                            logicalRoleMap.getLogicalRoles().get(i).getRoleName(), permCB));
                  }
                }
                for (int j = 0; j < logicalRoleMap.getRoleAssignments().length(); j++) {
                  String roleName = logicalRoleMap.getRoleAssignments().get(j).getRoleName();
                  List<String> logicalRoles = new ArrayList<String>();
                  for (int k = 0;
                      k
                          < logicalRoleMap
                              .getRoleAssignments()
                              .get(j)
                              .getAssignedLogicalRoles()
                              .length();
                      k++) {
                    logicalRoles.add(
                        logicalRoleMap
                            .getRoleAssignments()
                            .get(j)
                            .getAssignedLogicalRoles()
                            .get(k));
                  }
                  masterRoleMap.put(roleName, logicalRoles);
                }
              } else {
              }
            }
          });
    } catch (RequestException e) {
    }
  }
  private void initializeRoles(
      final String defaultValue, String serviceUrl, final ListBox listBox) {
    final String url = GWT.getHostPageBaseURL() + serviceUrl;
    RequestBuilder executableTypesRequestBuilder = new RequestBuilder(RequestBuilder.GET, url);
    executableTypesRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
    executableTypesRequestBuilder.setHeader("accept", "application/xml");
    try {
      executableTypesRequestBuilder.sendRequest(
          null,
          new RequestCallback() {

            public void onError(Request request, Throwable exception) {
              displayErrorInMessageBox(
                  Messages.getString("Error"), exception.getLocalizedMessage());
            }

            public void onResponseReceived(Request request, Response response) {
              listBox.clear();
              NativeEvent event = com.google.gwt.dom.client.Document.get().createChangeEvent();
              String txt = response.getText();
              Document doc = XMLParser.parse(txt);
              NodeList roles = doc.getElementsByTagName("roles");
              for (int i = 0; i < roles.getLength(); i++) {
                Node roleNode = roles.item(i);
                String role = roleNode.getFirstChild().getNodeValue();
                listBox.addItem(role);
                if (!StringUtils.isEmpty(defaultValue)) {
                  if (role.equals(defaultValue)) {
                    listBox.setSelectedIndex(i);
                    DomEvent.fireNativeEvent(event, listBox);
                  }
                }
              }
              if (listBox.getSelectedIndex() == -1 && listBox.getItemCount() > 0) {
                listBox.setSelectedIndex(0);
                DomEvent.fireNativeEvent(event, listBox);
              }
            }
          });
    } catch (RequestException e) {
      displayErrorInMessageBox(Messages.getString("Error"), e.getLocalizedMessage());
    }
  }
  public void fetchAllRoles(final ArrayList<String> existing) {

    try {
      final String url =
          GWT.getHostPageBaseURL() + "api/userrolelist/permission-roles"; // $NON-NLS-1$
      RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url);
      // This header is required to force Internet Explorer to not cache values from the GET
      // response.
      requestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
      requestBuilder.setHeader("accept", "application/json");
      requestBuilder.sendRequest(
          null,
          new RequestCallback() {

            public void onError(Request request, Throwable caught) {
              MessageDialogBox dialogBox =
                  new MessageDialogBox(
                      Messages.getString("error"),
                      Messages.getString("couldNotGetRoles"),
                      false,
                      false,
                      true); //$NON-NLS-1$ //$NON-NLS-2$
              dialogBox.center();
            }

            public void onResponseReceived(Request request, Response response) {
              JsArrayString roles = parseRolesJson(JsonUtils.escapeJsonForEval(response.getText()));
              // filter out existing
              rolesListBox.clear();
              for (int i = 0; i < roles.length(); i++) {
                String role = roles.get(i);
                if (!existing.contains(role)) {
                  rolesListBox.addItem(role);
                }
              }
            }
          });
    } catch (RequestException e) {
      Window.alert(e.getMessage());
    }
  }
  private void buildHeaders(RequestBuilder requestBuilder, String xsrfToken, RestAction<?> action)
      throws ActionException {
    String path = action.getPath();
    List<RestParameter> actionParams = action.getHeaderParams();
    Collection<RestParameter> applicableGlobalParams =
        globalHeaderParams.get(action.getHttpMethod());

    // By setting the most generic headers first, we make sure they can be overridden by more
    // specific ones
    requestBuilder.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    requestBuilder.setHeader(HttpHeaders.CONTENT_TYPE, JSON_UTF8);

    if (!isAbsoluteUrl(path)) {
      requestBuilder.setHeader(MODULE_BASE_HEADER, baseUrl);
    }

    if (!Strings.isNullOrEmpty(xsrfToken)) {
      requestBuilder.setHeader(securityHeaderName, xsrfToken);
    }

    for (RestParameter parameter : applicableGlobalParams) {
      String value = parameter.getStringValue();

      if (value != null) {
        requestBuilder.setHeader(parameter.getName(), value);
      }
    }

    for (RestParameter param : actionParams) {
      requestBuilder.setHeader(param.getName(), param.getStringValue());
    }
  }
  private void showScheduleEmailDialog(final JSONObject schedule) {
    try {
      final String url = GWT.getHostPageBaseURL() + "api/mantle/isAuthenticated"; // $NON-NLS-1$
      RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url);
      requestBuilder.setHeader("accept", "text/plain"); // $NON-NLS-1$ //$NON-NLS-2$
      requestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
      requestBuilder.sendRequest(
          null,
          new RequestCallback() {

            public void onError(Request request, Throwable caught) {
              MantleLoginDialog.performLogin(
                  new AsyncCallback<Boolean>() {

                    public void onFailure(Throwable caught) {}

                    public void onSuccess(Boolean result) {
                      showScheduleEmailDialog(schedule);
                    }
                  });
            }

            public void onResponseReceived(Request request, Response response) {
              JSONObject scheduleRequest = (JSONObject) JSONParser.parseStrict(schedule.toString());
              if (scheduleEmailDialog == null) {
                scheduleEmailDialog =
                    new ScheduleEmailDialog(
                        ScheduleRecurrenceDialog.this, filePath, scheduleRequest, null, editJob);
                scheduleEmailDialog.setCallback(callback);
              } else {
                scheduleEmailDialog.setJobSchedule(scheduleRequest);
              }
              scheduleEmailDialog.center();
              hide();
            }
          });
    } catch (RequestException e) {
      Window.alert(e.getMessage());
    }
  }
示例#28
0
 private RequestBuilder chooseRequestBuilder(final ModelNode operation) {
   RequestBuilder requestBuilder;
   final String op = operation.get(OP).asString();
   if (READ_RESOURCE_DESCRIPTION_OPERATION.equals(op)) {
     String endpoint = endpointConfig.getUrl();
     if (endpoint.endsWith("/")) {
       endpoint = endpoint.substring(0, endpoint.length() - 1);
     }
     String descriptionUrl = endpoint + descriptionOperationToUrl(operation);
     requestBuilder =
         new RequestBuilder(
             RequestBuilder.GET, com.google.gwt.http.client.URL.encode(descriptionUrl));
     requestBuilder.setHeader(HEADER_ACCEPT, DMR_ENCODED);
     requestBuilder.setHeader(HEADER_CONTENT_TYPE, DMR_ENCODED);
     requestBuilder.setIncludeCredentials(true);
     requestBuilder.setRequestData(null);
   } else {
     requestBuilder = postRequestBuilder();
     requestBuilder.setRequestData(operation.toBase64String());
   }
   return requestBuilder;
 }
  private void initializeActionBaseSecurityElements() {
    final String url = GWT.getHostPageBaseURL() + "api/userroledao/logicalRoleMap";
    RequestBuilder executableTypesRequestBuilder = new RequestBuilder(RequestBuilder.GET, url);
    executableTypesRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
    executableTypesRequestBuilder.setHeader("accept", "application/json");
    try {
      executableTypesRequestBuilder.sendRequest(
          null,
          new RequestCallback() {

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

            public void onResponseReceived(Request request, Response response) {
              String roleMappings = response.getText();
              rolesPermissionsPanel.initializeActionBaseSecurityElements(roleMappings);
              systemRolesPermissionsPanel.initializeActionBaseSecurityElements(roleMappings);
            }
          });
    } catch (RequestException e) {
      // ignored
    }
  }
  private void saveSecuritySettings(final AsyncCallback<Boolean> callback) {
    JSONObject jsNewRoleAssignments = new JSONObject();
    JSONArray jsLogicalRoleAssignments = new JSONArray();
    int x = 0;
    for (Map.Entry<String, List<String>> roleAssignment : newRoleAssignments.entrySet()) {
      JSONArray jsLogicalRoles = new JSONArray();
      int y = 0;
      for (String logicalRoleName : roleAssignment.getValue()) {
        jsLogicalRoles.set(y++, new JSONString(logicalRoleName));
      }
      JSONObject jsRoleAssignment = new JSONObject();
      jsRoleAssignment.put("roleName", new JSONString(roleAssignment.getKey()));
      jsRoleAssignment.put("logicalRoles", jsLogicalRoles);
      jsLogicalRoleAssignments.set(x++, jsRoleAssignment);
    }
    jsNewRoleAssignments.put("logicalRoleAssignments", jsLogicalRoleAssignments);
    RequestBuilder saveSettingRequestBuilder =
        new RequestBuilder(RequestBuilder.PUT, contextURL + "api/userrole/roleAssignments");
    saveSettingRequestBuilder.setHeader(
        "Content-Type", "application/json"); // $NON-NLS-1$//$NON-NLS-2$
    WaitPopup.getInstance().setVisible(true);
    try {
      saveSettingRequestBuilder.sendRequest(
          jsNewRoleAssignments.toString(),
          new RequestCallback() {

            @Override
            public void onError(Request request, Throwable exception) {
              WaitPopup.getInstance().setVisible(false);
              callback.onFailure(exception);
            }

            @Override
            public void onResponseReceived(Request request, Response response) {
              WaitPopup.getInstance().setVisible(false);
              if (response.getStatusCode() == 200) {
                masterRoleMap.putAll(newRoleAssignments);
                newRoleAssignments.clear();
                callback.onSuccess(true);
              } else {
                callback.onSuccess(false);
              }
            }
          });
    } catch (RequestException e) {
      WaitPopup.getInstance().setVisible(false);
      callback.onFailure(e);
    }
  }