Ejemplo n.º 1
0
  /**
   * Return URL to identity consolidator GUI with optional ?target= param having current Perun GUI
   * URL.
   *
   * @param target TRUE if use ?target= param in identity consolidator URL / FALSE otherwise
   * @return URL to identity consolidator
   */
  public static String getIdentityConsolidatorLink(boolean target) {

    // always use URL of machine, where GUI runs
    String baseUrl = Window.Location.getProtocol() + "//" + Window.Location.getHost();

    // FIXME - production consolidator is still using old URL scheme
    final String URL_KRB = baseUrl + "/perun-identity-consolidator-krb/";
    final String URL_FED = baseUrl + "/perun-identity-consolidator-fed/";
    final String URL_CERT = baseUrl + "/perun-identity-consolidator-cert/";
    String rpc = "";
    String link = "";

    if (PerunWebSession.getInstance().getRpcServer() != null) {
      rpc = PerunWebSession.getInstance().getRpcServer();
    }

    if (rpc.equalsIgnoreCase("krb")) {
      link = URL_KRB;
    } else if (rpc.equalsIgnoreCase("fed")) {
      link = URL_FED;
    } else if (rpc.equalsIgnoreCase("cert")) {
      link = URL_CERT;
    } else {
      // KRB AS BACKUP - "default"
      link = URL_KRB;
    }

    if (target) {
      link += "?target=" + Window.Location.getHref();
    }

    return link;
  }
Ejemplo n.º 2
0
 public void open() {
   if (fromSelf) {
     session
         .getUiElements()
         .getBreadcrumbs()
         .setLocation(
             MainMenu.USER,
             "My publications",
             CabinetTabs.URL
                 + UrlMapper.TAB_NAME_SEPARATOR
                 + "userpubs?user="******"Publications",
             CabinetTabs.URL + UrlMapper.TAB_NAME_SEPARATOR + "all",
             publication.getTitle(),
             getUrlWithParameters());
   }
 }
Ejemplo n.º 3
0
  /**
   * Return URL to Password change GUI for selected namespace
   *
   * @param namespace namespace where we want to reset password
   * @return URL to password reset GUI
   */
  public static String getPasswordResetLink(String namespace) {

    String value =
        PerunWebSession.getInstance().getConfiguration().getCustomProperty("getPasswordResetUrl");

    if (value != null && !value.isEmpty()) {

      // PWD-RESET URL IS CONFIGURED AS FIXED
      if (namespace != null && !namespace.isEmpty()) {
        return value + "?login-namespace=" + namespace;
      } else {
        return value;
      }

    } else {

      // USE RELATIVE PWD-RESET URL

      String baseUrl = Window.Location.getProtocol() + "//" + Window.Location.getHost();

      if (!Utils.isDevel()) {

        // VALID URL FOR PRODUCTION

        String rpc = "";
        if (PerunWebSession.getInstance().getRpcServer() != null) {
          rpc = PerunWebSession.getInstance().getRpcServer();
        }

        if (rpc.equalsIgnoreCase("krb")) {
          baseUrl += "/krb";
        } else if (rpc.equalsIgnoreCase("fed")) {
          baseUrl += "/fed";
        } else if (rpc.equalsIgnoreCase("forceAuthn-fed")) {
          baseUrl += "/fed-force";
        } else if (rpc.equalsIgnoreCase("cert")) {
          baseUrl += "/cert";
        } else if (rpc.equalsIgnoreCase("einfra")) {
          baseUrl += "/krb-einfra";
        } else {
          // KRB AS BACKUP - "default"
          baseUrl += "/krb";
        }

        baseUrl += "/pwd-reset/";

      } else {

        // VALID URL FOR DEVEL
        baseUrl += "/PasswordResetKrb.html";
      }

      if (namespace != null && !namespace.isEmpty()) {
        return baseUrl + "?login-namespace=" + namespace;
      } else {
        return baseUrl;
      }
    }
  }
Ejemplo n.º 4
0
  public boolean isAuthorized() {

    if (session.isVoAdmin(voId) || session.isVoObserver(voId) || session.isGroupAdmin(groupId)) {
      return true;
    } else {
      return false;
    }
  }
Ejemplo n.º 5
0
 public void open() {
   session.getUiElements().getMenu().openMenu(MainMenu.FACILITY_ADMIN);
   session.getUiElements().getBreadcrumbs().setLocation(facility, "", "");
   if (facility != null) {
     session.setActiveFacility(facility);
   } else {
     session.setActiveFacilityId(facilityId);
   }
 }
Ejemplo n.º 6
0
  /**
   * Returns TRUE if logged to Devel instance of Perun
   *
   * @return TRUE if instance of Perun is Devel / FALSE otherwise
   */
  public static boolean isDevel() {

    if (PerunWebSession.getInstance().getConfiguration() != null) {
      String value = PerunWebSession.getInstance().getConfiguration().getCustomProperty("isDevel");
      if (value != null && !value.isEmpty()) {
        return Boolean.parseBoolean(value);
      }
    }
    return false;
  }
Ejemplo n.º 7
0
  /**
   * Returns URL of Perun`s logo
   *
   * <p>if not set, use default: "img/logo11.png"
   *
   * @return URL of Perun`s logo
   */
  public static String logoUrl() {

    if (PerunWebSession.getInstance().getConfiguration() != null) {
      String value = PerunWebSession.getInstance().getConfiguration().getCustomProperty("logoUrl");
      if (value != null && !value.isEmpty()) {
        return value;
      }
    }
    return "img/logo11.png";
  }
Ejemplo n.º 8
0
  public void open() {

    session.getUiElements().getMenu().openMenu(MainMenu.GROUP_ADMIN);
    session.getUiElements().getBreadcrumbs().setLocation(group, "Settings", getUrlWithParameters());
    if (group != null) {
      session.setActiveGroup(group);
      return;
    }
    session.setActiveGroupId(groupId);
  }
Ejemplo n.º 9
0
  /**
   * Returns default RT queue for errors reporting
   *
   * @return default RT queue for errors reporting as string
   */
  public static String defaultRtQueue() {

    if (PerunWebSession.getInstance().getConfiguration() != null) {
      String value =
          PerunWebSession.getInstance().getConfiguration().getCustomProperty("defaultRtQueue");
      if (value != null && !value.isEmpty()) {
        return value;
      }
    }
    return "";
  }
Ejemplo n.º 10
0
  /**
   * Returns public key part of Re-Captcha widget (by GOOGLE) which is used for anonymous access to
   * application form.
   *
   * <p>If public key is not present, return null
   *
   * @return Re-Captcha public key
   */
  public static String getReCaptchaPublicKey() {

    if (PerunWebSession.getInstance().getConfiguration() != null) {
      String value =
          PerunWebSession.getInstance()
              .getConfiguration()
              .getCustomProperty("getReCaptchaPublicKey");
      if (value != null && !value.isEmpty()) {
        return value;
      }
    }
    return null;
  }
Ejemplo n.º 11
0
  /**
   * Returns default RT queue for errors reporting
   *
   * @return default RT queue for errors reporting as string
   */
  public static String vosManagerMembersGroup() {

    if (PerunWebSession.getInstance().getConfiguration() != null) {
      String value =
          PerunWebSession.getInstance()
              .getConfiguration()
              .getCustomProperty("vosManagerMembersGroup");
      if (value != null && !value.isEmpty()) {
        return value;
      }
    }
    return "";
  }
Ejemplo n.º 12
0
  /**
   * Returns address to perun support
   *
   * @return support email as string
   */
  public static String perunReportEmailAddress() {

    if (PerunWebSession.getInstance().getConfiguration() != null) {
      String value =
          PerunWebSession.getInstance()
              .getConfiguration()
              .getCustomProperty("perunReportEmailAddress");
      if (value != null && !value.isEmpty()) {
        return value;
      }
    }
    return "";
  }
Ejemplo n.º 13
0
 public boolean isAuthorized() {
   if (session.isSelf()) {
     return true;
   } else {
     return false;
   }
 }
 /** Called, when operation finishes successfully. */
 public void onFinished(JavaScriptObject jso) {
   setList(JsonUtils.<Publication>jsoAsList(jso));
   sortTable();
   session.getUiElements().setLogText("Publications loaded: " + list.size());
   events.onFinished(jso);
   loaderImage.loadingFinished();
 }
Ejemplo n.º 15
0
  public Widget draw() {

    VerticalPanel vp = new VerticalPanel();
    vp.getElement().setAttribute("style", "padding-top: 5px;");
    vp.setSize("100%", "100%");

    FindAllAuthors callback = new FindAllAuthors();
    CellTable<Author> table =
        callback.getTable(
            new FieldUpdater<Author, String>() {
              public void update(int index, Author object, String value) {
                if (session.isPerunAdmin()) {
                  session.getTabManager().addTab(new UsersPublicationsTabItem(object.getId()));
                }
              }
            });

    table.addStyleName("perun-table");
    ScrollPanel sp = new ScrollPanel();
    sp.add(table);
    sp.addStyleName("perun-tableScrollPanel");

    vp.add(sp);

    // resize perun table to correct size on screen
    session.getUiElements().resizeSmallTabPanel(sp, 350, this);

    this.contentWidget.setWidget(vp);

    return getWidget();
  }
Ejemplo n.º 16
0
 /** Called when loading successfully finishes. */
 public void onFinished(JavaScriptObject jso) {
   BasicOverlayType count = (BasicOverlayType) jso;
   session.getUiElements().setLogText("Loading members count finished: " + count.getInt());
   this.membersCountLabel.setText(String.valueOf(count.getInt()));
   this.hyp.setText(String.valueOf(count.getInt()));
   this.events.onFinished(jso);
 }
Ejemplo n.º 17
0
  public Widget draw() {

    // main panel
    VerticalPanel vp = new VerticalPanel();
    vp.getElement().setAttribute("style", "padding-top: 5px;");
    vp.setSize("100%", "100%");

    FindAllPublicationSystems call = new FindAllPublicationSystems();
    call.setCheckable(false);
    CellTable<PublicationSystem> table = call.getTable();
    table.addStyleName("perun-table");

    ScrollPanel sp = new ScrollPanel();
    sp.add(table);
    sp.addStyleName("perun-tableScrollPanel");

    vp.add(sp);

    // resize perun table to correct size on screen
    session.getUiElements().resizeSmallTabPanel(sp, 350, this);

    this.contentWidget.setWidget(vp);

    return getWidget();
  }
Ejemplo n.º 18
0
 /** Called, when operation finishes successfully. */
 public void onFinished(JavaScriptObject jso) {
   setList(JsonUtils.<ExtSource>jsoAsList(jso));
   sortTable();
   session.getUiElements().setLogText("Loading external sources finished: " + list.size());
   events.onFinished(jso);
   loaderImage.loadingFinished();
 }
  public boolean isAuthorized() {

    if (session.isFacilityAdmin(facility.getId())) {
      return true;
    } else {
      return false;
    }
  }
Ejemplo n.º 20
0
  public boolean isAuthorized() {

    if (session.isPerunAdmin()) {
      return true;
    } else {
      return false;
    }
  }
Ejemplo n.º 21
0
  public boolean isAuthorized() {

    if (session.isVoAdmin(voId)) {
      return true;
    } else {
      return false;
    }
  }
Ejemplo n.º 22
0
  /**
   * Returns list of supported namespaces names for password change / reset
   *
   * @return list of supported namespaces names
   */
  public static ArrayList<String> getSupportedPasswordNamespaces() {

    ArrayList<String> attributes = new ArrayList<String>();
    if (PerunWebSession.getInstance().getConfiguration() != null) {
      String value =
          PerunWebSession.getInstance()
              .getConfiguration()
              .getCustomProperty("getSupportedPasswordNamespaces");
      if (value != null && !value.isEmpty()) {
        String[] urns = value.split(",");
        for (int i = 0; i < urns.length; i++) {
          attributes.add(urns[i]);
        }
      }
    }
    return attributes;
  }
Ejemplo n.º 23
0
 /** Called, when operation finishes successfully. */
 public void onFinished(JavaScriptObject jso) {
   clearTable();
   for (Attribute a : JsonUtils.<Attribute>jsoAsList(jso)) {
     if (!a.getDefinition().equals("core")) {
       addToTable(a);
     }
   }
   sortTable();
   loaderImage.loadingFinished();
   session.getUiElements().setLogText("Resource required attributes loaded: " + list.size());
   events.onFinished(jso);
 }
Ejemplo n.º 24
0
/**
 * Request, which verifies captcha
 *
 * @author Pavel Zlamal <*****@*****.**>
 * @version $Id$
 */
public class VerifyCaptcha implements JsonCallback {

  // web session
  private PerunWebSession session = PerunWebSession.getInstance();

  // URL to call
  final String JSON_URL = "registrarManager/verifyCaptcha";

  // custom events
  private JsonCallbackEvents events = new JsonCallbackEvents();

  // application form
  private String challenge;
  private String response;

  /** Creates a new request */
  public VerifyCaptcha(String challenge, String response) {
    this.challenge = challenge;
    this.response = response;
  }

  /**
   * Creates a new request with custom events
   *
   * @param events Custom events
   */
  public VerifyCaptcha(String challenge, String response, JsonCallbackEvents events) {
    this.challenge = challenge;
    this.response = response;
    this.events = events;
  }

  @Override
  public void onFinished(JavaScriptObject jso) {
    events.onFinished(jso);
  }

  @Override
  public void onError(PerunError error) {
    events.onError(error);
  }

  @Override
  public void onLoadingStart() {
    events.onLoadingStart();
  }

  @Override
  public void retrieveData() {
    JsonClient js = new JsonClient();
    js.retrieveData(JSON_URL, "challenge=" + challenge + "&response=" + response, this);
  }
}
Ejemplo n.º 25
0
/**
 * Ajax query to load external sources to Perun from local file definition.
 *
 * @author Pavel Zlamal <*****@*****.**>
 */
public class LoadExtSourcesDefinitions implements JsonCallback {

  // session
  private PerunWebSession session = PerunWebSession.getInstance();
  // jsonCallback string
  private final String JSON_URL = "extSourcesManager/loadExtSourcesDefinitions";

  private JsonCallbackEvents events = new JsonCallbackEvents();

  /** Creates a new callback */
  public LoadExtSourcesDefinitions() {}

  /**
   * Creates a new callback
   *
   * @param events external events
   */
  public LoadExtSourcesDefinitions(JsonCallbackEvents events) {
    this.events = events;
  }

  /** Retrieve data from RPC */
  public void retrieveData() {
    JsonClient js = new JsonClient();
    js.retrieveData(JSON_URL, this);
  }

  /** Called, when an error occurs */
  public void onError(PerunError error) {
    session.getUiElements().setLogErrorText("Error while loading external sources.");
    events.onError(error);
  }

  /** Called, when loading starts */
  public void onLoadingStart() {
    session.getUiElements().setLogText("Loading external sources started.");
    events.onLoadingStart();
  }

  /** Called, when operation finishes successfully. */
  public void onFinished(JavaScriptObject jso) {
    session.getUiElements().setLogText("Loading external sources finished.");
    events.onFinished(jso);
  }
}
Ejemplo n.º 26
0
  /** Called when loading successfully finishes. */
  public void onFinished(JavaScriptObject jso) {

    applFormItems.clear();
    applFormItems.addAll(JsonUtils.<ApplicationFormItem>jsoAsList(jso));
    applFormGenerators.clear();

    if (settings) {
      prepareSettings(applFormItems);
    } else {
      prepareApplicationForm(applFormItems);
    }

    session
        .getUiElements()
        .setLogText(
            "Loading application form items in selected VO finished:" + applFormItems.size());
    events.onFinished(jso);
    loaderImage.loadingFinished();
  }
Ejemplo n.º 27
0
/**
 * Common request, which handles applications (VERIFY, REJECT, APPROVE, DELETE)
 *
 * @author Pavel Zlamal <*****@*****.**>
 */
public class HandleApplication {

  // web session
  private PerunWebSession session = PerunWebSession.getInstance();

  // URL to call
  final String JSON_URL_VERIFY = "registrarManager/verifyApplication";
  final String JSON_URL_APPROVE = "registrarManager/approveApplication";
  final String JSON_URL_REJECT = "registrarManager/rejectApplication";
  final String JSON_URL_DELETE = "registrarManager/deleteApplication";

  // custom events
  private JsonCallbackEvents events = new JsonCallbackEvents();

  // application form
  private int appId = 0;

  private String reason;

  /** Creates a new request */
  public HandleApplication() {}

  /**
   * Creates a new request with custom events
   *
   * @param events Custom events
   */
  public HandleApplication(JsonCallbackEvents events) {
    this.events = events;
  }

  /**
   * Verify application
   *
   * @param appId
   */
  public void verifyApplication(int appId) {

    this.appId = appId;

    // test arguments
    if (!this.testApplication()) {
      return;
    }

    // new events
    JsonCallbackEvents newEvents =
        new JsonCallbackEvents() {
          @Override
          public void onError(PerunError error) {
            session.getUiElements().setLogErrorText("Verifying application failed.");
            events.onError(error);
          };

          @Override
          public void onFinished(JavaScriptObject jso) {
            session.getUiElements().setLogSuccessText("Application verified.");
            events.onFinished(jso);
          };

          @Override
          public void onLoadingStart() {
            events.onLoadingStart();
          };
        };

    // sending data
    JsonPostClient jspc = new JsonPostClient(newEvents);
    jspc.sendData(JSON_URL_VERIFY, prepareJSONObject());
  }

  /**
   * Reject application
   *
   * @param appId
   * @param reason
   */
  public void rejectApplication(int appId, String reason) {

    this.appId = appId;
    this.reason = reason;

    // test arguments
    if (!this.testApplication()) {
      return;
    }

    // new events
    JsonCallbackEvents newEvents =
        new JsonCallbackEvents() {
          public void onError(PerunError error) {
            session.getUiElements().setLogErrorText("Rejecting application failed.");
            events.onError(error);
          };

          public void onFinished(JavaScriptObject jso) {
            session.getUiElements().setLogSuccessText("Application rejected.");
            events.onFinished(jso);
          };

          public void onLoadingStart() {
            events.onLoadingStart();
          };
        };

    // sending data
    JsonPostClient jspc = new JsonPostClient(newEvents);
    jspc.sendData(JSON_URL_REJECT, prepareJSONObject());
  }

  /**
   * Approve application
   *
   * @param app
   */
  public void approveApplication(final Application app) {

    this.appId = app.getId();

    // test arguments
    if (!this.testApplication()) {
      return;
    }

    // new events
    final JsonCallbackEvents newEvents =
        new JsonCallbackEvents() {
          @Override
          public void onError(PerunError error) {
            session.getUiElements().setLogErrorText("Approving application failed.");
            events.onError(error);
          }

          @Override
          public void onFinished(JavaScriptObject jso) {
            session.getUiElements().setLogSuccessText("Application approved.");
            events.onFinished(jso);
          }

          @Override
          public void onLoadingStart() {
            events.onLoadingStart();
          }
        };

    // check for similar users before approving

    JSONObject jso = new JSONObject();
    jso.put("appId", new JSONNumber(appId));

    if (app.getUser() != null) {

      // ok approve sending data
      JsonPostClient jspc = new JsonPostClient(newEvents);
      jspc.sendData(JSON_URL_APPROVE, prepareJSONObject());

    } else {

      JsonPostClient checkJspc =
          new JsonPostClient(
              new JsonCallbackEvents() {
                @Override
                public void onError(PerunError error) {
                  session.getUiElements().setLogErrorText("Approving application failed.");
                  events.onError(error);
                }

                @Override
                public void onFinished(JavaScriptObject jso) {

                  ArrayList<Identity> users = JsonUtils.jsoAsList(jso);
                  if (users != null && !users.isEmpty()) {

                    FlexTable ft = new FlexTable();
                    ft.setWidth("600px");
                    ft.setHTML(0, 0, "<p><strong>Following similar user(s) were found in system:");
                    ft.getFlexCellFormatter().setColSpan(0, 0, 3);

                    ft.setHTML(
                        1, 0, "<strong>" + ApplicationMessages.INSTANCE.name() + "</strong>");
                    ft.setHTML(
                        1, 1, "<strong>" + ApplicationMessages.INSTANCE.email() + "</strong>");
                    ft.setHTML(
                        1,
                        2,
                        "<strong>" + ApplicationMessages.INSTANCE.organization() + "</strong>");

                    int i = 2;

                    for (Identity user : users) {

                      ft.setHTML(i, 0, user.getName());

                      if (user.getEmail() != null && !user.getEmail().isEmpty()) {
                        ft.setHTML(i, 1, user.getEmail());
                      } else {
                        ft.setHTML(i, 1, "N/A");
                      }

                      if (user.getOrganization() != null && !user.getOrganization().isEmpty()) {
                        ft.setHTML(i, 2, user.getOrganization());
                      } else {
                        ft.setHTML(i, 2, "N/A");
                      }

                      i++;
                    }

                    String type = "";
                    if (app.getExtSourceType()
                        .equals("cz.metacentrum.perun.core.impl.ExtSourceX509")) {
                      type = "cert";
                    } else if (app.getExtSourceType()
                        .equals("cz.metacentrum.perun.core.impl.ExtSourceIdp")) {
                      type = "fed";
                    }

                    ft.setHTML(
                        i,
                        0,
                        "<p>Please contact new applicant with question, if he/she isn't already member of any other VO."
                            + "<ul><li>If YES, ask him/her to join identities at <a href=\""
                            + Utils.getIdentityConsolidatorLink(type, false)
                            + "\" target=\"_blank\">identity consolidator</a> before approving this application."
                            + "</li><li>If NO, you can approve this application anyway. "
                            + "</li><li>If UNSURE, contact <a href=\"mailto:"
                            + Utils.perunReportEmailAddress()
                            + "\">support</a> to help you.</li></ul>");

                    ft.getFlexCellFormatter().setColSpan(i, 0, 3);

                    i++;

                    ft.setHTML(
                        i, 0, "<strong>Do you wish to approve this application anyway ?</strong>");
                    ft.getFlexCellFormatter().setColSpan(i, 0, 3);

                    Confirm c =
                        new Confirm(
                            "Similar users found!",
                            ft,
                            new ClickHandler() {
                              @Override
                              public void onClick(ClickEvent clickEvent) {

                                // ok approve sending data
                                JsonPostClient jspc = new JsonPostClient(newEvents);
                                jspc.sendData(JSON_URL_APPROVE, prepareJSONObject());
                              }
                            },
                            new ClickHandler() {
                              @Override
                              public void onClick(ClickEvent clickEvent) {
                                events.onFinished(null);
                              }
                            },
                            true);

                    c.setOkButtonText("Approve");

                    c.setNonScrollable(true);
                    c.show();

                  } else {

                    // ok approve sending data
                    JsonPostClient jspc = new JsonPostClient(newEvents);
                    jspc.sendData(JSON_URL_APPROVE, prepareJSONObject());
                  }
                }

                @Override
                public void onLoadingStart() {
                  events.onLoadingStart();
                }
              });
      checkJspc.sendData("registrarManager/checkForSimilarUsers", jso);
    }
  }

  /**
   * Delete application
   *
   * @param appId
   */
  public void deleteApplication(int appId) {

    this.appId = appId;

    // test arguments
    if (!this.testApplication()) {
      return;
    }

    // new events
    JsonCallbackEvents newEvents =
        new JsonCallbackEvents() {
          @Override
          public void onError(PerunError error) {
            session.getUiElements().setLogErrorText("Deleting application failed.");
            events.onError(error);
          };

          @Override
          public void onFinished(JavaScriptObject jso) {
            session.getUiElements().setLogSuccessText("Application deleted.");
            events.onFinished(jso);
          };

          @Override
          public void onLoadingStart() {
            events.onLoadingStart();
          };
        };

    // sending data
    JsonPostClient jspc = new JsonPostClient(newEvents);
    jspc.sendData(JSON_URL_DELETE, prepareJSONObject());
  }

  private boolean testApplication() {

    boolean result = true;
    String errorMsg = "";

    if (appId == 0) {
      errorMsg += "Application ID can't be 0.";
      result = false;
    }

    if (errorMsg.length() > 0) {
      UiElements.generateAlert("Parameter error", errorMsg);
    }

    return result;
  }

  /**
   * Prepares a JSON object.
   *
   * @return JSONObject - the whole query
   */
  private JSONObject prepareJSONObject() {
    // query
    JSONObject query = new JSONObject();
    query.put("id", new JSONNumber(appId));

    if (reason != null) {
      query.put("reason", new JSONString(reason));
    }

    return query;
  }
}
 /** Called, when loading starts */
 public void onLoadingStart() {
   session.getUiElements().setLogText("Loading publications started.");
   events.onLoadingStart();
 }
 /** Called, when an error occurs */
 public void onError(PerunError error) {
   session.getUiElements().setLogErrorText("Error while loading publications.");
   loaderImage.loadingError(error);
   events.onError(error);
 }
/**
 * Finds publications in external source
 *
 * @author Vaclav Mach <*****@*****.**>
 * @version $Id$
 */
public class FindExternalPublications implements JsonCallback, JsonCallbackTable<Publication> {

  // session
  private PerunWebSession session = PerunWebSession.getInstance();
  // json url
  private static final String JSON_URL = "cabinetManager/findExternalPublications";
  // Data provider
  private ListDataProvider<Publication> dataProvider = new ListDataProvider<Publication>();
  // table
  private PerunTable<Publication> table;
  // table data
  private ArrayList<Publication> list = new ArrayList<Publication>();
  // Selection model
  final MultiSelectionModel<Publication> selectionModel =
      new MultiSelectionModel<Publication>(
          new GeneralKeyProvider<Publication>() {
            @Override
            public Object getKey(Publication o) {
              return o.getExternalId();
            }
          });
  // External events
  private JsonCallbackEvents events = new JsonCallbackEvents();
  // loader image
  private AjaxLoaderImage loaderImage = new AjaxLoaderImage();

  // parameters
  private int userId;

  private int yearSince = 0;

  private int yearTill = Integer.MAX_VALUE;

  private String namespace = "";

  private boolean checkable = true;

  /**
   * Creates a new request
   *
   * @param userId User ID
   */
  public FindExternalPublications(int userId) {
    this.userId = userId;
  }

  /**
   * Creates a new request
   *
   * @param userId User ID
   * @param yearSince Year since
   * @param yearTill Year till
   * @param namespace namespace (MU, ZCU)
   */
  public FindExternalPublications(int userId, int yearSince, int yearTill, String namespace) {
    this(userId);
    this.yearSince = yearSince;
    this.yearTill = yearTill;
    this.namespace = namespace;
  }

  /**
   * Creates a new request
   *
   * @param userId User ID
   * @param events events
   */
  public FindExternalPublications(int userId, JsonCallbackEvents events) {
    this(userId);
    this.events = events;
  }

  /**
   * Creates a new request
   *
   * @param userId User ID
   * @param yearSince Year since
   * @param yearTill Year till
   * @param namespace namespace (MU, ZCU)
   * @param events events
   */
  public FindExternalPublications(
      int userId, int yearSince, int yearTill, String namespace, JsonCallbackEvents events) {
    this(userId, yearSince, yearTill, namespace);
    this.events = events;
  }

  /**
   * Returns table with publications
   *
   * @return table
   */
  public CellTable<Publication> getTable() {
    retrieveData();
    return this.getEmptyTable();
  }

  /**
   * Returns table with publications
   *
   * @return table
   */
  public CellTable<Publication> getEmptyTable() {

    // Table data provider.
    dataProvider = new ListDataProvider<Publication>(list);

    // Cell table
    table = new PerunTable<Publication>(list);
    table.removeRowCountChangeHandler();
    table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.DISABLED);

    // Connect the table to the data provider.
    dataProvider.addDataDisplay(table);

    // Sorting
    ListHandler<Publication> columnSortHandler =
        new ListHandler<Publication>(dataProvider.getList());
    table.addColumnSortHandler(columnSortHandler);

    // table selection
    table.setSelectionModel(
        selectionModel, DefaultSelectionEventManager.<Publication>createCheckboxManager());

    // set empty content & loader
    table.setEmptyTableWidget(
        loaderImage.prepareToSearch(
            "Please select external pub. system and year range to search for publications for import."));

    // show checkbox column
    if (this.checkable) {
      table.addCheckBoxColumn();
    }

    /*
    // CATEGORY COLUMN
    ArrayList<String> categories = new ArrayList<String>();
    categories.add("Bodované v RIVu");
    categories.add("Nebodované v RIVu");
    categories.add("Příspěvek do ročenky");
    categories.add("Výjimečné výsledky");
    categories.add("Jiné");

    Column<Publication, String> categoryColumn = new Column<Publication, String>(new SelectionCell(categories)){
    	@Override
    	public String getValue(Publication object) {
    		// category ID as string, 0 if not set
    		int id = object.getCategoryId();
    		if (id == 0) {
    			// set default == 21/Bodované v RIVu to object
    			object.setCategoryId(21);
    		}
    		if (id == 21) {
    			return "Bodované v RIVu";
    		} else if (id == 22) {
    			return "Nebodované v RIVu";
    		} else if (id == 23) {
    			return "Výjimečné výsledky";
    		} else if (id == 24) {
    			return "Příspěvek do ročenky";
    		} else if (id == 25) {
    			return "Jiné";
    		} else {
    			return String.valueOf(id); // return ID if no match
    		}
    	}
    };
    categoryColumn.setFieldUpdater(new FieldUpdater<Publication, String>() {
    	public void update(int index, Publication object, String value) {

    		int id = 0;
    		if (value.equalsIgnoreCase("Bodované v RIVu")) {
    			id = 21;
    		} else if (value.equalsIgnoreCase("Nebodované v RIVu")) {
    			id = 22;
    		} else if (value.equalsIgnoreCase("Příspěvek do ročenky")) {
    			id = 24;
    		} else if (value.equalsIgnoreCase("Výjimečné výsledky")) {
    			id = 23;
    		} else if (value.equalsIgnoreCase("Jiné")) {
    			id = 25;
    		}
    		object.setCategoryId(id);
    		selectionModel.setSelected(object, true);

    	}
    });
    table.addColumn(categoryColumn, "Category");

    // NOT USEFULL => DISABLED
    // EXTERNAL ID
    TextColumn<Publication> externalIdColumn = new TextColumn<Publication>() {
    	public String getValue(Publication object) {
    		return String.valueOf(object.getExternalId());
    	};
    };
    externalIdColumn.setSortable(true);
    columnSortHandler.setComparator(externalIdColumn, new PublicationComparator(PublicationComparator.Column.EXTERNAL_ID));
    table.addColumn(externalIdColumn, "External Id");
     */

    // TITLE COLUMN
    TextColumn<Publication> titleColumn =
        new TextColumn<Publication>() {
          public String getValue(Publication object) {
            return object.getTitle();
          };
        };
    titleColumn.setSortable(true);
    columnSortHandler.setComparator(
        titleColumn, new PublicationComparator(PublicationComparator.Column.TITLE));
    table.addColumn(titleColumn, "Title");

    // AUTHORS COLUMN
    TextColumn<Publication> authorColumn =
        new TextColumn<Publication>() {
          public String getValue(Publication object) {
            return object.getAuthorsFormatted();
          };
        };
    authorColumn.setSortable(true);
    columnSortHandler.setComparator(
        authorColumn, new PublicationComparator(PublicationComparator.Column.AUTHORS));
    table.addColumn(authorColumn, "Authors");

    // YEAR COLUMN
    TextColumn<Publication> yearColumn =
        new TextColumn<Publication>() {
          public String getValue(Publication object) {
            return String.valueOf(object.getYear());
          };
        };
    yearColumn.setSortable(true);
    columnSortHandler.setComparator(
        yearColumn, new PublicationComparator(PublicationComparator.Column.YEAR));
    table.addColumn(yearColumn, "Year");

    // ISBN COLUMN
    TextColumn<Publication> isbnColumn =
        new TextColumn<Publication>() {
          public String getValue(Publication object) {
            return object.getIsbn();
          };
        };
    isbnColumn.setSortable(true);
    columnSortHandler.setComparator(
        isbnColumn, new PublicationComparator(PublicationComparator.Column.ISBN));
    table.addColumn(isbnColumn, "ISBN");

    // CITE COLUMN
    Column<Publication, String> citaceColumn =
        JsonUtils.addColumn(
            new JsonUtils.GetValue<Publication, String>() {
              public String getValue(Publication object) {
                return "Cite";
              }
            },
            new FieldUpdater<Publication, String>() {
              public void update(int index, Publication object, String value) {
                SimplePanel sp = new SimplePanel();
                sp.add(new HTML(object.getMain()));
                Confirm cf = new Confirm("Cite publication", sp, true);
                cf.show();
              };
            });

    table.addColumn(citaceColumn, "Cite");

    return table;
  }

  /** Retrieves data from RPC */
  public void retrieveData() {
    JsonClient js = new JsonClient(60000); // 1 minute to retrieve data from external source
    js.retrieveData(
        JSON_URL,
        "user="******"&yearSince="
            + yearSince
            + "&yearTill="
            + yearTill
            + "&pubSysNamespace="
            + namespace,
        this);
    return;
  }

  /** Sorts table by objects Name */
  public void sortTable() {
    list = new TableSorter<Publication>().sortByPublicationTitle(getList());
    dataProvider.flush();
    dataProvider.refresh();
  }

  /**
   * Add object as new row to table
   *
   * @param object Publication to be added as new row
   */
  public void addToTable(Publication object) {
    list.add(object);
    dataProvider.flush();
    dataProvider.refresh();
  }

  /**
   * Removes object as row from table
   *
   * @param object Publication to be removed as row
   */
  public void removeFromTable(Publication object) {
    list.remove(object);
    selectionModel.getSelectedSet().remove(object);
    dataProvider.flush();
    dataProvider.refresh();
  }

  /** Clear all table content */
  public void clearTable() {
    loaderImage.loadingStart();
    list.clear();
    selectionModel.clear();
    dataProvider.flush();
    dataProvider.refresh();
  }

  /** Clears list of selected items */
  public void clearTableSelectedSet() {
    selectionModel.clear();
  }

  /**
   * Return selected items from list
   *
   * @return return list of checked items
   */
  public ArrayList<Publication> getTableSelectedList() {
    return JsonUtils.setToList(selectionModel.getSelectedSet());
  }

  /** Called, when an error occurs */
  public void onError(PerunError error) {
    session.getUiElements().setLogErrorText("Error while loading publications.");
    loaderImage.loadingError(error);
    events.onError(error);
  }

  /** Called, when loading starts */
  public void onLoadingStart() {
    session.getUiElements().setLogText("Loading publications started.");
    events.onLoadingStart();
  }

  /** Called, when operation finishes successfully. */
  public void onFinished(JavaScriptObject jso) {
    setList(JsonUtils.<Publication>jsoAsList(jso));
    sortTable();
    session.getUiElements().setLogText("Publications loaded: " + list.size());
    events.onFinished(jso);
    loaderImage.loadingFinished();
  }

  public void insertToTable(int index, Publication object) {
    list.add(index, object);
    dataProvider.flush();
    dataProvider.refresh();
  }

  public void setEditable(boolean editable) {
    // TODO Auto-generated method stub
  }

  public void setCheckable(boolean checkable) {
    this.checkable = checkable;
  }

  public void setList(ArrayList<Publication> list) {
    clearTable();
    this.list.addAll(list);
    dataProvider.flush();
    dataProvider.refresh();
  }

  public ArrayList<Publication> getList() {
    return this.list;
  }

  /** Set user Id */
  public void setUser(int userId) {
    this.userId = userId;
  }

  /** Set year since */
  public void setYearSince(int year) {
    this.yearSince = year;
  }

  /** Set year till */
  public void setYearTill(int year) {
    this.yearTill = year;
  }

  /** Set pub sys namespace */
  public void setNamespace(String namespace) {
    this.namespace = namespace;
  }
}