/**
   * Deletes a meeting from the database
   *
   * <p>- Requires a cookie for the session user - Requires a meetingId request parameter for the
   * HTTP GET
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void deletemeetingAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    if (req.getMethod() == HttpMethod.Get) {

      // Get the meeting
      int meetingId = Integer.parseInt(req.getParameter("meetingId"));
      MeetingManager meetingMan = new MeetingManager();
      Meeting meeting = meetingMan.get(meetingId);
      meetingMan.deleteMeeting(meetingId);

      // Update the User Session to remove meeting
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      List<Meeting> adminMeetings = userSession.getUser().getMeetings();

      for (int i = 0; i < adminMeetings.size(); i++) {
        Meeting m = adminMeetings.get(i);
        if (m.getId() == meeting.getId()) {
          adminMeetings.remove(i);
          break;
        }
      }

      redirectToLocal(req, res, "/home/dashboard");
      return;

    } else if (req.getMethod() == HttpMethod.Post) {
      httpNotFound(req, res);
    }
  }
  /**
   * Creates a Discussion Post
   *
   * <p>- Requires a cookie for the session user - Requires a comment and threadId request parameter
   * for the POST
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void createPostAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<>();

    if (req.getMethod() == HttpMethod.Post) {
      DiscussionManager dm = new DiscussionManager();

      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");

      // Create the discussion post
      DiscussionPost post = new DiscussionPost();
      post.setUserId(userSession.getUserId());
      post.setMessage(req.getParameter("comment"));
      post.setThreadId(Integer.parseInt(req.getParameter("threadId")));

      dm.createPost(post);

      redirectToLocal(req, res, "/group/discussion/?threadId=" + req.getParameter("threadId"));
    } else {
      httpNotFound(req, res);
    }
  }
Exemplo n.º 3
0
  protected void connectSession() throws JSchException {
    if (session != null) {
      if (session.isConnected()) {
        session.disconnect();
      }
      session = null;
    }

    AutomationLogger.getInstance().info("Connectting...");

    if (StringUtil.notEmpty(user)) {
      session = jsch.getSession(user, host, 22);
      session.setPassword(password);
    } else if (auth != null) {
      session = auth.getSession(host);
    } else {
      throw new ItemNotFoundException("Authentication is missing!");
    }

    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
    AutomationLogger.getInstance().info("Connected");
  }
Exemplo n.º 4
0
 /**
  * Creates new databases.
  *
  * @throws IOException I/O exception
  */
 @Test
 public final void create() throws IOException {
   session.create(NAME, new ArrayInput(""));
   assertEqual("", session.query("db:open('" + NAME + "')").execute());
   session.create(NAME, new ArrayInput("<X/>"));
   assertEqual("<X/>", session.query("db:open('" + NAME + "')").execute());
 }
  /** {@inheritDoc} */
  @Override
  public void txEnd(GridCacheTx tx, boolean commit) throws GridException {
    init();

    Session ses = tx.removeMeta(ATTR_SES);

    if (ses != null) {
      Transaction hTx = ses.getTransaction();

      if (hTx != null) {
        try {
          if (commit) {
            ses.flush();

            hTx.commit();
          } else hTx.rollback();

          if (log.isDebugEnabled())
            log.debug("Transaction ended [xid=" + tx.xid() + ", commit=" + commit + ']');
        } catch (HibernateException e) {
          throw new GridException(
              "Failed to end transaction [xid=" + tx.xid() + ", commit=" + commit + ']', e);
        } finally {
          ses.close();
        }
      }
    }
  }
Exemplo n.º 6
0
  public static void sendEmail(
      InternetAddress from, InternetAddress to, String content, String requester)
      throws MessagingException, UnsupportedEncodingException {

    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("MN Traffic Generation is used by " + requester);
    message.setContent(content, "text/plain");

    message.addRecipient(Message.RecipientType.TO, to);

    InternetAddress[] replyto = new InternetAddress[1];
    replyto[0] = from;

    message.setFrom(from);
    message.setReplyTo(replyto);
    message.setSender(from);

    transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));

    transport.close();
  }
Exemplo n.º 7
0
  public static void main(String[] args) throws MessagingException, IOException {
    IMAPFolder folder = null;
    Store store = null;
    String subject = null;
    Flag flag = null;
    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");
      props.setProperty("mail.imap.host", "imap.googlemail.com");
      SimpleAuthenticator authenticator =
          new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy");
      Session session = Session.getDefaultInstance(props, null);
      // Session session = Session.getDefaultInstance(props, authenticator);

      store = session.getStore("imaps");
      //          store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");
      // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");

      store.connect("*****@*****.**", "hhy8611hhy");
      // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email
      // account
      folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account

      if (!folder.isOpen()) folder.open(Folder.READ_WRITE);
      Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages();
      System.out.println("No of get Messages : " + messages.length);
      System.out.println("No of Messages : " + folder.getMessageCount());
      System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
      System.out.println("No of New Messages : " + folder.getNewMessageCount());
      System.out.println(messages.length);
      for (int i = 0; i < messages.length; i++) {

        System.out.println(
            "*****************************************************************************");
        System.out.println("MESSAGE " + (i + 1) + ":");
        Message msg = messages[i];
        // System.out.println(msg.getMessageNumber());
        // Object String;
        // System.out.println(folder.getUID(msg)

        subject = msg.getSubject();

        System.out.println("Subject: " + subject);
        System.out.println("From: " + msg.getFrom()[0]);
        System.out.println("To: " + msg.getAllRecipients()[0]);
        System.out.println("Date: " + msg.getReceivedDate());
        System.out.println("Size: " + msg.getSize());
        System.out.println(msg.getFlags());
        System.out.println("Body: \n" + msg.getContent());
        System.out.println(msg.getContentType());
      }
    } finally {
      if (folder != null && folder.isOpen()) {
        folder.close(true);
      }
      if (store != null) {
        store.close();
      }
    }
  }
Exemplo n.º 8
0
  public static void main(String[] args) throws MessagingException, IOException {
    Properties props = new Properties();
    try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) {
      props.load(in);
    }
    List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8"));

    String from = lines.get(0);
    String to = lines.get(1);
    String subject = lines.get(2);

    StringBuilder builder = new StringBuilder();
    for (int i = 3; i < lines.size(); i++) {
      builder.append(lines.get(i));
      builder.append("\n");
    }

    Console console = System.console();
    String password = new String(console.readPassword("Password: "));

    Session mailSession = Session.getDefaultInstance(props);
    // mailSession.setDebug(true);
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(builder.toString());
    Transport tr = mailSession.getTransport();
    try {
      tr.connect(null, password);
      tr.sendMessage(message, message.getAllRecipients());
    } finally {
      tr.close();
    }
  }
  /** {@inheritDoc} */
  @SuppressWarnings({"unchecked", "RedundantTypeArguments"})
  @Override
  public V load(@Nullable GridCacheTx tx, K key) throws GridException {
    init();

    if (log.isDebugEnabled()) log.debug("Store load [key=" + key + ", tx=" + tx + ']');

    Session ses = session(tx);

    try {
      GridCacheHibernateBlobStoreEntry entry =
          (GridCacheHibernateBlobStoreEntry)
              ses.get(GridCacheHibernateBlobStoreEntry.class, toBytes(key));

      if (entry == null) return null;

      return fromBytes(entry.getValue());
    } catch (HibernateException e) {
      rollback(ses, tx);

      throw new GridException("Failed to load value from cache store with key: " + key, e);
    } finally {
      end(ses, tx);
    }
  }
  /**
   * Gets Hibernate session.
   *
   * @param tx Cache transaction.
   * @return Session.
   */
  Session session(@Nullable GridCacheTx tx) {
    Session ses;

    if (tx != null) {
      ses = tx.meta(ATTR_SES);

      if (ses == null) {
        ses = sesFactory.openSession();

        ses.beginTransaction();

        // Store session in transaction metadata, so it can be accessed
        // for other operations on the same transaction.
        tx.addMeta(ATTR_SES, ses);

        if (log.isDebugEnabled())
          log.debug("Hibernate session open [ses=" + ses + ", tx=" + tx.xid() + "]");
      }
    } else {
      ses = sesFactory.openSession();

      ses.beginTransaction();
    }

    return ses;
  }
Exemplo n.º 11
0
  /**
   * Runs a query with an external variable declaration.
   *
   * @throws IOException I/O exception
   */
  @Test
  public void queryBindSequence() throws IOException {
    Query query = session.query("declare variable $a external; $a");
    query.bind("a", "1\u00012", "xs:integer");
    assertEqual("1", query.next());
    assertEqual("2", query.next());
    query.close();

    query = session.query("declare variable $a external; $a");
    query.bind("a", "09\u0002xs:hexBinary\u00012", "xs:integer");
    assertEqual("09", query.next());
    assertEqual("2", query.next());
    query.close();

    query = session.query("declare variable $a external; $a");
    query.bind("a", Seq.get(new Item[] {Int.get(1), Str.get("X")}, 2));
    assertEqual("1", query.next());
    assertEqual("X", query.next());
    query.close();

    query = session.query("declare variable $a external; $a");
    query.bind("a", IntSeq.get(new long[] {1, 2}, AtomType.INT));
    assertEqual("1", query.next());
    assertEqual("2", query.next());
    query.close();

    query = session.query("declare variable $a external; $a");
    query.bind("a", IntSeq.get(new long[] {1, 2}, AtomType.INT), "xs:integer");
    assertEqual("1", query.next());
    assertEqual("2", query.next());
    query.close();
  }
  /** {@inheritDoc} */
  @Override
  public void put(@Nullable GridCacheTx tx, K key, @Nullable V val) throws GridException {
    init();

    if (log.isDebugEnabled())
      log.debug("Store put [key=" + key + ", val=" + val + ", tx=" + tx + ']');

    if (val == null) {
      remove(tx, key);

      return;
    }

    Session ses = session(tx);

    try {
      GridCacheHibernateBlobStoreEntry entry =
          new GridCacheHibernateBlobStoreEntry(toBytes(key), toBytes(val));

      ses.saveOrUpdate(entry);
    } catch (HibernateException e) {
      rollback(ses, tx);

      throw new GridException(
          "Failed to put value to cache store [key=" + key + ", val" + val + "]", e);
    } finally {
      end(ses, tx);
    }
  }
Exemplo n.º 13
0
  public void mail(String toAddress, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.ssl.enable", true);
    Authenticator authenticator = null;
    if (login) {
      props.put("mail.smtp.auth", true);
      authenticator =
          new Authenticator() {
            private PasswordAuthentication pa = new PasswordAuthentication(username, password);

            @Override
            public PasswordAuthentication getPasswordAuthentication() {
              return pa;
            }
          };
    }

    Session s = Session.getInstance(props, authenticator);
    s.setDebug(debug);
    MimeMessage email = new MimeMessage(s);
    try {
      email.setFrom(new InternetAddress(from));
      email.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
      email.setSubject(subject);
      email.setSentDate(new Date());
      email.setText(body);
      Transport.send(email);
    } catch (MessagingException ex) {
      ex.printStackTrace();
    }
  }
Exemplo n.º 14
0
 /**
  * Runs a query with additional serialization parameters.
  *
  * @throws IOException I/O exception
  */
 @Test
 public void querySerial1() throws IOException {
   session.execute("set serializer wrap-prefix=db,wrap-uri=ns");
   final Query query = session.query(WRAPPER + "()");
   assertTrue("Result expected.", query.more());
   assertEqual("<db:results xmlns:db=\"ns\"/>", query.next());
   assertFalse("No result expected.", query.more());
 }
  /**
   * Determines whether a vaild session exists for the contact of remote machine.
   *
   * @param sshContact ID of SSH Contact
   * @return <tt>true</tt> if the session is connected <tt>false</tt> otherwise
   */
  public boolean isSessionValid(ContactSSH sshContact) {
    Session sshSession = sshContact.getSSHSession();
    if (sshSession != null) if (sshSession.isConnected()) return true;

    // remove reference to an unconnected SSH Session, if any
    sshContact.setSSHSession(null);
    return false;
  }
Exemplo n.º 16
0
 /**
  * Stores binary content.
  *
  * @throws IOException I/O exception
  */
 @Test
 public void storeBinary() throws IOException {
   session.execute("create db " + NAME);
   session.store("X", new ArrayInput(new byte[] {-128, -2, -1, 0, 1, 127}));
   assertEqual(
       "-128 -2 -1 0 1 127",
       session.query(_CONVERT_BINARY_TO_BYTES.args(_DB_RETRIEVE.args(NAME, "X"))).execute());
 }
Exemplo n.º 17
0
 /**
  * Adds documents to a database.
  *
  * @throws IOException I/O exception
  */
 @Test
 public final void add() throws IOException {
   session.execute("create db " + NAME);
   session.add(NAME, new ArrayInput("<X/>"));
   assertEqual("1", session.query("count(" + _DB_OPEN.args(NAME) + ')').execute());
   for (int i = 0; i < 9; i++) session.add(NAME, new ArrayInput("<X/>"));
   assertEqual("10", session.query("count(" + _DB_OPEN.args(NAME) + ')').execute());
 }
Exemplo n.º 18
0
  /**
   * Delete document or folder.
   *
   * @throws IOException I/O exception
   */
  protected void del() throws IOException {
    final Session session = http.session();
    session.execute(new Open(db));
    session.execute(new Delete(path));

    // create dummy, if parent is an empty folder
    final int ix = path.lastIndexOf(SEP);
    if (ix > 0) createDummy(path.substring(0, ix));
  }
Exemplo n.º 19
0
 /** Stops a session. */
 @After
 public final void stopSession() {
   try {
     if (cleanup) session.execute(new DropDB(NAME));
     session.close();
   } catch (final IOException ex) {
     fail(Util.message(ex));
   }
 }
Exemplo n.º 20
0
 /**
  * Queries empty content.
  *
  * @throws IOException I/O exception
  */
 @Test
 public void queryEmptyBinary() throws IOException {
   session.execute("create db " + NAME);
   session.store("X", new ArrayInput(""));
   assertEqual("", session.execute("xquery " + RAW + _DB_RETRIEVE.args(NAME, "X")));
   assertEqual("", session.query(RAW + _DB_RETRIEVE.args(NAME, "X")).execute());
   final Query q = session.query(RAW + _DB_RETRIEVE.args(NAME, "X"));
   assertTrue(q.more());
   assertEqual("", q.next());
   assertNull(q.next());
 }
  /**
   * Ends hibernate session.
   *
   * @param ses Hibernate session.
   * @param tx Cache ongoing transaction.
   */
  private void end(Session ses, GridCacheTx tx) {
    // Commit only if there is no cache transaction,
    // otherwise txEnd() will do all required work.
    if (tx == null) {
      Transaction hTx = ses.getTransaction();

      if (hTx != null && hTx.isActive()) hTx.commit();

      ses.close();
    }
  }
Exemplo n.º 22
0
  /**
   * Runs a query with an external variable declaration.
   *
   * @throws IOException I/O exception
   */
  @Test
  public void queryBindInt() throws IOException {
    Query query = session.query("declare variable $a as xs:integer external; $a");
    query.bind("a", "5", "xs:integer");
    assertEqual("5", query.next());
    query.close();

    query = session.query("declare variable $a external; $a");
    query.bind("a", Int.get(1), "xs:integer");
    assertEqual("1", query.next());
    query.close();
  }
Exemplo n.º 23
0
 /**
  * Runs two queries in parallel.
  *
  * @throws IOException I/O exception
  */
 @Test
 public void queryParallel() throws IOException {
   final Query query1 = session.query("1 to 2");
   final Query query2 = session.query("reverse(3 to 4)");
   assertEqual("1", query1.next());
   assertEqual("4", query2.next());
   assertEqual("2", query1.next());
   assertEqual("3", query2.next());
   assertNull(query1.next());
   assertNull(query2.next());
   query1.close();
   query2.close();
 }
Exemplo n.º 24
0
  /**
   * Rename document or folder.
   *
   * @param n new name
   * @throws IOException I/O exception
   */
  protected void rename(final String n) throws IOException {
    final Session session = http.session();
    session.execute(new Open(db));
    session.execute(new Rename(path, n));

    // create dummy, if old parent is an empty folder
    final int i1 = path.lastIndexOf(SEP);
    if (i1 > 0) createDummy(path.substring(0, i1));

    // delete dummy, if new parent is an empty folder
    final int i2 = n.lastIndexOf(SEP);
    if (i2 > 0) deleteDummy(n.substring(0, i2));
  }
Exemplo n.º 25
0
 /** Clean up method. */
 @After
 public void cleanUp() {
   try {
     testSession.close();
     adminSession.execute(new DropDB(RENAMED));
     adminSession.execute(new DropDB(NAME));
     adminSession.close();
     // give the server some time to clean up the sessions before next test
     Performance.sleep(100);
   } catch (final Exception ex) {
     fail(Util.message(ex));
   }
 }
Exemplo n.º 26
0
 /**
  * Start the application
  *
  * @throws IOException if there is a problem with connection
  * @throws InterruptedException if thread was interrupted
  */
 private void start() throws IOException, InterruptedException {
   Connection c = new Connection(myHost.getHostName(), myHost.getPort());
   try {
     configureKnownHosts(c);
     c.connect(new HostKeyVerifier());
     authenticate(c);
     final Session s = c.openSession();
     try {
       s.execCommand(myCommand);
       // Note that stdin is not being waited using semaphore.
       // Instead, the SSH process waits for remote process exit
       // if remote process exited, none is interested in stdin
       // anyway.
       forward("stdin", s.getStdin(), System.in, false);
       forward("stdout", System.out, s.getStdout(), true);
       forward("stderr", System.err, s.getStderr(), true);
       myForwardCompleted.acquire(2); // wait only for stderr and stdout
       s.waitForCondition(ChannelCondition.EXIT_STATUS, Long.MAX_VALUE);
       Integer exitStatus = s.getExitStatus();
       if (exitStatus == null) {
         // broken exit status
         exitStatus = 1;
       }
       System.exit(exitStatus.intValue() == 0 ? myExitCode : exitStatus.intValue());
     } finally {
       s.close();
     }
   } finally {
     c.close();
   }
 }
  public void testReferenceLinkAttribute() {
    Session ssn = SessionManager.getSession();
    DataObject user = ssn.create(getModelName() + ".User");
    user.set("id", BigInteger.valueOf(0));
    user.set("email", "*****@*****.**");
    user.set("firstName", "foo");
    user.set("lastNames", "bar");
    user.save();

    DataObject[] images = new DataObject[2];
    for (int i = 0; i < images.length; i++) {
      images[i] = ssn.create(getModelName() + ".Image");
      images[i].set("id", BigInteger.valueOf(i));
      byte[] bytes = "This is the image.".getBytes();
      images[i].set("bytes", bytes);
      images[i].save();
    }

    // set image
    user.set("image", images[0]);
    user.save();

    // retrieve and then update caption
    DataAssociationCursor dac = ((DataAssociation) images[0].get("users")).cursor();
    dac.next();
    assertNull(dac.getLinkProperty("caption"));
    assertEquals(user, dac.getDataObject());
    DataObject link = dac.getLink();
    link.set("caption", "caption");
    link.save();

    dac = ((DataAssociation) images[0].get("users")).cursor();
    dac.next();
    assertEquals("caption", dac.getLinkProperty("caption"));
    assertEquals(1L, ((DataAssociation) images[0].get("users")).size());

    // set new image as image
    user.set("image", images[1]);
    user.save();

    // check that old image is no longer associated with user
    assertEquals(0L, ((DataAssociation) images[0].get("users")).size());

    // check that new image is associated with user and has no caption
    dac = ((DataAssociation) images[1].get("users")).cursor();
    dac.next();
    assertNull(dac.getLinkProperty("caption"));
    assertEquals(1L, ((DataAssociation) images[1].get("users")).size());
  }
  /** {@inheritDoc} */
  @Override
  public void onSessionStart(CacheStoreSession ses) {
    if (ses.attachment() == null) {
      try {
        Session hibSes = sesFactory.openSession();

        ses.attach(hibSes);

        if (ses.isWithinTransaction()) hibSes.beginTransaction();
      } catch (HibernateException e) {
        throw new CacheWriterException(
            "Failed to start store session [tx=" + ses.transaction() + ']', e);
      }
    }
  }
 protected void createSessionsTable(List<Session> sessions) {
   table().attr("cellpadding", "0", "cellspacing", "0", "border", "0", "class", "display");
   thead();
   tr();
   createThs("Id", "Last Used");
   end();
   end();
   tbody();
   for (Session s : sessions) {
     tr();
     createTds(s.getId(), formatDurationHMS(System.currentTimeMillis() - s.getLastUsed()));
     end();
   }
   end();
   end();
 }
Exemplo n.º 30
0
 /**
  * Performs the specified query n times and and returns the result.
  *
  * @param query query to be evaluated
  * @param n number of runs
  * @return resulting string
  * @throws IOException I/O exception
  */
 protected static String eval(final int n, final String query) throws IOException {
   // loop through number of runs for a single query
   check();
   String result = "";
   for (int rn = 0; rn < n; ++rn) result = session.execute(new XQuery(query));
   return result;
 }