/** Tests sending a request from a ClientTransaction. */
  public void testSendRequest() {
    try {
      Request invite = createTiInviteRequest(null, null, null);
      RequestEvent receivedRequestEvent = null;
      ClientTransaction tran = null;
      try {
        tran = tiSipProvider.getNewClientTransaction(invite);
        eventCollector.collectRequestEvent(riSipProvider);
        tran.sendRequest();
        waitForMessage();
        receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
        assertNotNull("The sent request was not received by the RI!", receivedRequestEvent);
        assertNotNull(
            "The sent request was not received by the RI!", receivedRequestEvent.getRequest());
      } catch (TransactionUnavailableException exc) {
        throw new TiUnexpectedError(
            "A TransactionUnavailableException was thrown while trying to "
                + "create a new client transaction",
            exc);
      } catch (SipException exc) {
        exc.printStackTrace();
        fail("The SipException was thrown while trying to send the request.");
      } catch (TooManyListenersException exc) {
        throw new TckInternalError(
            "A  TooManyListenersException was thrown while trying "
                + "to add a SipListener to an RI SipProvider",
            exc);
      }
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }

    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
 /** Sends a single invite request and checks whether it arrives normally at the other end. */
 public void testSendRequest() {
   try {
     // create an empty invite request.
     Request invite = createTiInviteRequest(null, null, null);
     Request receivedRequest = null;
     try {
       // Send using TI and collect using RI
       eventCollector.collectRequestEvent(riSipProvider);
       waitForMessage();
       tiSipProvider.sendRequest(invite);
       waitForMessage();
       RequestEvent receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
       assertNotNull("The sent request was not received at the other end!", receivedRequestEvent);
       assertNotNull(
           "The sent request was not received at the other end!",
           receivedRequestEvent.getRequest());
     } catch (TooManyListenersException ex) {
       throw new TckInternalError(
           "The following exception was thrown while trying to add "
               + "a SipListener to an RI SipProvider",
           ex);
     } catch (SipException ex) {
       ex.printStackTrace();
       fail("A SipException exception was thrown while " + "trying to send a request.");
     }
   } catch (Throwable exc) {
     exc.printStackTrace();
     fail(exc.getClass().getName() + ": " + exc.getMessage());
   }
   assertTrue(new Exception().getStackTrace()[0].toString(), true);
 }
  /**
   * Creates an invite request using the Tested Implementation and then tests creating a cancel for
   * the same invite request.
   */
  public void testCreateCancel() {
    try {
      Request invite = createTiInviteRequest(null, null, null);
      ClientTransaction tran = null;
      try {
        tran = tiSipProvider.getNewClientTransaction(invite);
      } catch (TransactionUnavailableException exc) {
        throw new TiUnexpectedError(
            "A TransactionUnavailableException was thrown while trying to "
                + "create a new client transaction",
            exc);
      }
      Request cancel = null;
      try {
        cancel = tran.createCancel();
      } catch (SipException ex) {
        ex.printStackTrace();
        fail("Failed to create cancel request!");
      }
      assertEquals(
          "The created request did not have a CANCEL method.", cancel.getMethod(), Request.CANCEL);
      assertEquals(
          "Request-URIs of the original and the cancel request do not match",
          cancel.getRequestURI(),
          invite.getRequestURI());
      assertEquals(
          "Call-IDs of the original and the cancel request do not match",
          cancel.getHeader(CallIdHeader.NAME),
          invite.getHeader(CallIdHeader.NAME));
      assertEquals(
          "ToHeaders of the original and the cancel request do not match",
          cancel.getHeader(ToHeader.NAME),
          invite.getHeader(ToHeader.NAME));
      assertTrue(
          "The CSeqHeader's sequence number of the original and "
              + "the cancel request do not match",
          ((CSeqHeader) cancel.getHeader(CSeqHeader.NAME)).getSequenceNumber()
              == ((CSeqHeader) invite.getHeader(CSeqHeader.NAME)).getSequenceNumber());
      assertEquals(
          "The CSeqHeader's method of the cancel request was not CANCEL",
          ((CSeqHeader) cancel.getHeader(CSeqHeader.NAME)).getMethod(),
          Request.CANCEL);
      assertTrue(
          "There was no ViaHeader in the cancel request",
          cancel.getHeaders(ViaHeader.NAME).hasNext());
      Iterator cancelVias = cancel.getHeaders(ViaHeader.NAME);
      ViaHeader cancelVia = ((ViaHeader) cancelVias.next());
      ViaHeader inviteVia = ((ViaHeader) invite.getHeaders(ViaHeader.NAME).next());
      assertEquals(
          "ViaHeaders of the original and the cancel request do not match!", cancelVia, inviteVia);
      assertFalse("Cancel request had more than one ViaHeader.", cancelVias.hasNext());
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }

    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
  /**
   * Sends a request from the TI, generates a response at the RI side, sends it back and checks
   * whether it arrives at the TI.
   */
  public void testReceiveResponse() {
    try {
      // 1. Create and send the original request

      Request invite = createTiInviteRequest(null, null, null);
      RequestEvent receivedRequestEvent = null;
      try {
        // Send using TI and collect using RI
        eventCollector.collectRequestEvent(riSipProvider);
        tiSipProvider.sendRequest(invite);
        waitForMessage();
        receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
        if (receivedRequestEvent == null || receivedRequestEvent.getRequest() == null)
          throw new TckInternalError("The sent request was not received by the RI!");
      } catch (TooManyListenersException ex) {
        throw new TckInternalError(
            "A TooManyListenersException was thrown while trying to add "
                + "a SipListener to an RI SipProvider.",
            ex);
      } catch (SipException ex) {
        throw new TiUnexpectedError("The TI failed to send the request!", ex);
      }
      Request receivedRequest = receivedRequestEvent.getRequest();
      // 2. Create and send the response
      Response ok = null;
      try {
        ok = riMessageFactory.createResponse(Response.OK, receivedRequest);
        addStatus(receivedRequest, ok);
      } catch (ParseException ex) {
        throw new TckInternalError("Failed to create an OK response!", ex);
      }
      // Send the response using the RI and collect using TI
      try {
        eventCollector.collectResponseEvent(tiSipProvider);
      } catch (TooManyListenersException ex) {
        throw new TiUnexpectedError("Error while trying to add riSipProvider");
      }
      try {
        riSipProvider.sendResponse(ok);
      } catch (SipException ex) {
        throw new TckInternalError("Could not send back the response", ex);
      }
      waitForMessage();
      ResponseEvent responseEvent = eventCollector.extractCollectedResponseEvent();
      // 3. Now ... do we like what we got?
      assertNotNull("The TI failed to receive the response!", responseEvent);
      assertNotNull("The TI failed to receive the response!", responseEvent.getResponse());
      assertNull(
          "The TI had implicitly created a client transaction! "
              + "Transactions should only be created explicitly using "
              + "the SipProvider.getNewXxxTransaction() method.",
          responseEvent.getClientTransaction());
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }
    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
  private void sendProcessingError(Throwable t, ServletResponse response) {

    String stackTrace = getStackTrace(t);

    if (stackTrace != null && !stackTrace.equals("")) {

      try {

        response.setContentType("text/html");
        PrintStream ps = new PrintStream(response.getOutputStream());
        PrintWriter pw = new PrintWriter(ps);
        pw.print("<html>\n<head>\n</head>\n<body>\n"); // NOI18N

        // PENDING! Localize this for next official release
        pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
        pw.print(stackTrace);
        pw.print("</pre></body>\n</html>"); // NOI18N
        pw.close();
        ps.close();
        response.getOutputStream().close();
        ;
      } catch (Exception ex) {
      }
    } else {
      try {
        PrintStream ps = new PrintStream(response.getOutputStream());
        t.printStackTrace(ps);
        ps.close();
        response.getOutputStream().close();
        ;
      } catch (Exception ex) {
      }
    }
  }
Example #6
0
  public static void ProcessCustomerPayment(Connection conn) {
    // This function updates is_paid so billing staff can keep track of the payments customers have
    // made

    int c_id = BooksAThousand.getIntFromShell("Enter customer ID: ");

    try {
      Statement statement =
          conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
      ResultSet rs =
          statement.executeQuery(
              "select customer_id, isbn, quantity, price, customer_order_date, is_paid"
                  + " from customer_order where customer_id="
                  + c_id
                  + " and is_paid='N'");
      if (rs.next()) {
        System.out.println("Outstanding payments:");
        System.out.printf(
            "Order  %-10s %-5s %-5s %-10s %-10s\n", "ISBN", "Quant", "Price", "Total", "Date");
        Date date;
        int i = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy hh:mm");
        do {
          i++;
          date = rs.getDate(5);
          System.out.printf(
              "%-5s: %-10s %-5d %-5d %-10d %-10s \n",
              i,
              rs.getInt(2),
              rs.getInt(3),
              rs.getInt(4),
              rs.getInt(3) * rs.getInt(4),
              sdf.format(date));
        } while (rs.next());
        int order = BooksAThousand.getIntFromShell("Which order to mark as paid: ");
        rs.absolute(i);
        rs.updateString(6, "Y");
        rs.updateRow();
        System.out.println("Update successful.");

      } else {
        System.out.println("This user has no unpaid orders");
      }
    } catch (Throwable e) {
      e.printStackTrace();
    }
  }
Example #7
0
  public static void GenerateCustomerBill(Connection conn) {
    // We intended to produce the bills over certain time periods but
    // we will offer an option to check just the last 3 months.
    try {
      int c_id = BooksAThousand.getIntFromShell("Enter customer ID: ");
      Statement statement = conn.createStatement();
      ResultSet rs =
          statement.executeQuery("select address, name from customer where customer_id = " + c_id);
      rs.next();
      String address = rs.getString(1);
      String name = rs.getString(2);
      rs =
          statement.executeQuery(
              "select customer_id, isbn, quantity, price, customer_order_date"
                  + " from customer_order where customer_id="
                  + c_id
                  + " and is_paid='N'");
      float total = 0;
      if (rs.next()) {
        Date date;
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy hh:mm");
        System.out.println("\n" + address);
        System.out.println("\nDear " + name + ", \nBelow are your unpaid orders. Pay up.\n");
        System.out.printf(
            "%-10s %-20s %-5s %-8s %-11s\n", "ISBN", "Date", "Quant", "Price", "Total");

        do {
          total += rs.getInt(3) * rs.getFloat(4);
          date = rs.getDate(5);
          System.out.printf(
              "%-10s %-20s %-5d $%-7.2f $%-10.2f \n",
              rs.getInt(2),
              sdf.format(date),
              rs.getInt(3),
              rs.getFloat(4),
              rs.getInt(3) * rs.getFloat(4));
        } while (rs.next());
        System.out.printf("Total: $%.2f\n", total);
      } else {
        System.out.println("This user has no unpaid orders");
      }
    } catch (Throwable e) {
      e.printStackTrace();
    }
  }
 /**
  * Send a simple invite request from the RI and check whether it is properly delivered by the TI
  * SipProvider
  */
 public void testReceiveRequest() {
   try {
     // create an empty invite request.
     Request invite = createRiInviteRequest(null, null, null);
     RequestEvent receivedRequestEvent = null;
     try {
       // Send using RI and collect using TI
       eventCollector.collectRequestEvent(tiSipProvider);
       riSipProvider.sendRequest(invite);
       waitForMessage();
       receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
       assertNotNull("The sent request was not received at the other end!", receivedRequestEvent);
       assertNotNull(
           "The sent request was not received at the other end!",
           receivedRequestEvent.getRequest());
     } catch (TooManyListenersException ex) {
       // This time adding the listener is (sort of) part of the test
       // so we fail instead of just "throwing on" the exc
       ex.printStackTrace();
       fail(
           "A TooManyListenersException was thrown while trying to add "
               + "a SipListener to a TI SipProvider.");
     } catch (SipException ex) {
       throw new TckInternalError("The RI failed to send the request!", ex);
     }
     // question: should we compare sent and received request?
     // my opinion: finding a discrepancy while comparing requests
     // would most probably mean a parse error and parsing is not what
     // we are currently testing
     // Transaction initiating requests should not have a server transaction
     // associated with them as the application might decide to handle the
     // request statelessly
     assertNull(
         "The Tested Implementation has implicitly created a ServerTransaction "
             + "for the received request. Transactions should only be created "
             + "explicitly using the SipProvider.getNewXxxTransaction() method.",
         receivedRequestEvent.getServerTransaction());
   } catch (Throwable exc) {
     exc.printStackTrace();
     fail(exc.getClass().getName() + ": " + exc.getMessage());
   }
   assertTrue(new Exception().getStackTrace()[0].toString(), true);
 }
 /**
  * Create an error message based on the parser's error message.
  *
  * @param pex the parse exception
  * @param fn the name of the file which had been parsed.
  * @return an error message
  */
 public static String fixedParserErrorMessage(Throwable pex, String fn) {
   String m = pex.getMessage();
   if (m == null) {
     return "Unknown Syntax Error in File " + fn;
   } else {
     return "Syntax Error in File "
         + fn
         + "\n"
         + m.replace((char) 13, ' ').replace((char) 10, ' ');
   }
 }
Example #10
0
 /** Test whether new ClientTransactions are properly created. */
 public void testGetNewClientTransaction() {
   try {
     Request invite = createTiInviteRequest(null, null, null);
     ClientTransaction tran = null;
     try {
       tran = tiSipProvider.getNewClientTransaction(invite);
     } catch (TransactionUnavailableException exc) {
       exc.printStackTrace();
       fail(
           "A TransactionUnavailableException was thrown while trying to "
               + "create a new client transaction");
     }
     assertNotNull(
         "A null ClientTransaction was returned by SipProvider." + "getNewClientTransaction().",
         tran);
     String tranBranch = tran.getBranchId();
     String reqBranch = ((ViaHeader) invite.getHeader(ViaHeader.NAME)).getBranch();
     assertEquals(
         "The newly created transaction did not have the same "
             + "branch id as the request that created it",
         tranBranch,
         reqBranch);
     assertNotNull(
         "The newly created transaction returned a null Dialog. "
             + "Please check the docs on Transaction.getDialog()",
         tran.getDialog());
     assertNotNull(
         "The transaction's getRequest() method returned a null Request ", tran.getRequest());
     assertEquals(
         "The transaction's getRequest() method returned a Request "
             + "that did not match the one that we used to create it!",
         tran.getRequest(),
         invite);
   } catch (Throwable exc) {
     exc.printStackTrace();
     fail(exc.getClass().getName() + ": " + exc.getMessage());
   }
   assertTrue(new Exception().getStackTrace()[0].toString(), true);
 }
  public static String getStackTrace(Throwable t) {

    String stackTrace = null;

    try {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      t.printStackTrace(pw);
      pw.close();
      sw.close();
      stackTrace = sw.getBuffer().toString();
    } catch (Exception ex) {
    }
    return stackTrace;
  }
  /** Tests creating of ACK requests. */
  public void testCreateAck() {
    try {
      // 1. Create and send the original request

      Request invite = createTiInviteRequest(null, null, null);
      RequestEvent receivedRequestEvent = null;
      ClientTransaction tran = null;
      try {
        tran = tiSipProvider.getNewClientTransaction(invite);
        eventCollector.collectRequestEvent(riSipProvider);
        tran.sendRequest();
        waitForMessage();
        receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
        if (receivedRequestEvent == null || receivedRequestEvent.getRequest() == null)
          throw new TiUnexpectedError("The sent request was not received by the RI!");
      } catch (TooManyListenersException ex) {
        throw new TckInternalError(
            "A TooManyListenersException was thrown while trying to add "
                + "a SipListener to an RI SipProvider.",
            ex);
      } catch (SipException ex) {
        throw new TiUnexpectedError("The TI failed to send the request!", ex);
      }
      Request receivedRequest = receivedRequestEvent.getRequest();
      // 2. Create and send the response
      Response ok = null;
      try {
        ok = riMessageFactory.createResponse(Response.OK, receivedRequest);
      } catch (ParseException ex) {
        throw new TckInternalError("Failed to create an OK response!", ex);
      }
      // Send the response using the RI and collect using TI
      try {
        eventCollector.collectResponseEvent(tiSipProvider);
      } catch (TooManyListenersException ex) {
        throw new TiUnexpectedError("Error while trying to add riSipProvider");
      }
      try {
        riSipProvider.sendResponse(ok);
      } catch (SipException ex) {
        throw new TckInternalError("Could not send back the response", ex);
      }
      waitForMessage();
      ResponseEvent responseEvent = eventCollector.extractCollectedResponseEvent();
      // 3. Now let's create the ack
      if (responseEvent == null || responseEvent.getResponse() == null)
        throw new TiUnexpectedError("The TI failed to receive the response!");
      if (responseEvent.getClientTransaction() != tran)
        throw new TiUnexpectedError(
            "The TI has associated a new ClientTransaction to a response "
                + "instead of using existing one!");
      Request ack = null;
      try {
        ack = tran.createAck();
      } catch (SipException ex) {
        ex.printStackTrace();
        fail("A SipException was thrown while creating an ack request");
      }
      assertNotNull("ClientTransaction.createAck returned null!", ack);
      assertEquals(
          "The created request did not have a CANCEL method.", ack.getMethod(), Request.ACK);
      assertEquals(
          "Request-URIs of the original and the ack request do not match",
          ack.getRequestURI(),
          invite.getRequestURI());
      assertEquals(
          "Call-IDs of the original and the ack request do not match",
          ack.getHeader(CallIdHeader.NAME),
          invite.getHeader(CallIdHeader.NAME));
      assertEquals(
          "ToHeaders of the original and the ack request do not match",
          ack.getHeader(ToHeader.NAME),
          invite.getHeader(ToHeader.NAME));
      assertTrue(
          "The CSeqHeader's sequence number of the original and " + "the ack request do not match",
          ((CSeqHeader) ack.getHeader(CSeqHeader.NAME)).getSequenceNumber()
              == ((CSeqHeader) invite.getHeader(CSeqHeader.NAME)).getSequenceNumber());
      assertEquals(
          "The CSeqHeader's method of the ack request was not ACK",
          ((CSeqHeader) ack.getHeader(CSeqHeader.NAME)).getMethod(),
          Request.ACK);
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }

    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
Example #13
0
 /**
  * Sends a request from the RI and tests whether the tested implementation properly creates a
  * ServerTransaction.
  */
 public void testGetNewServerTransaction() {
   try {
     Request invite = createRiInviteRequest(null, null, null);
     ServerTransaction tran = null;
     RequestEvent receivedRequestEvent = null;
     try {
       // Send using RI and collect using TI
       eventCollector.collectRequestEvent(tiSipProvider);
       riSipProvider.sendRequest(invite);
       waitForMessage();
       receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
       if (receivedRequestEvent == null || receivedRequestEvent.getRequest() == null)
         throw new TiUnexpectedError("The sent request was not received by the RI!");
     } catch (TooManyListenersException ex) {
       throw new TiUnexpectedError(
           "A TooManyListenersException was thrown while trying to add "
               + "a SipListener to a TI SipProvider.",
           ex);
     } catch (SipException ex) {
       throw new TckInternalError("The RI failed to send the request!", ex);
     }
     try {
       tran = tiSipProvider.getNewServerTransaction(invite);
     } catch (TransactionUnavailableException exc) {
       exc.printStackTrace();
       fail(
           "A TransactionUnavailableException was thrown while trying to "
               + "create a new client transaction");
     } catch (TransactionAlreadyExistsException exc) {
       exc.printStackTrace();
       fail(
           "A TransactionAlreadyExistsException was thrown while trying to "
               + "create a new server transaction");
     }
     assertNotNull(
         "A null ServerTransaction was returned by SipProvider." + "getNewServerTransaction().",
         tran);
     String tranBranch = tran.getBranchId();
     String reqBranch = ((ViaHeader) invite.getHeader(ViaHeader.NAME)).getBranch();
     assertEquals(
         "The newly created transaction did not have the same "
             + "branch id as the request that created it!",
         tranBranch,
         reqBranch);
     assertNotNull(
         "The newly created transaction returned a null Dialog. "
             + "Please check the docs on Transaction.getDialog()",
         tran.getDialog());
     assertNotNull(
         "The transaction's getRequest() method returned a null Request ", tran.getRequest());
     assertEquals(
         "The transaction's getRequest() method returned a Request "
             + "that did not match the one that we used to create it!",
         tran.getRequest(),
         invite);
   } catch (Throwable exc) {
     exc.printStackTrace();
     fail(exc.getClass().getName() + ": " + exc.getMessage());
   }
   assertTrue(new Exception().getStackTrace()[0].toString(), true);
 }
Example #14
0
  /**
   * Sends a request from the RI, generates a response at the TI side, sends it back and checks
   * whether it arrives at the RI.
   */
  public void testSendResponse() {
    try {
      // 1. Create and send the original request

      Request invite = createRiInviteRequest(null, null, null);
      RequestEvent receivedRequestEvent = null;
      try {
        // Send using RI and collect using TI
        eventCollector.collectRequestEvent(tiSipProvider);
        riSipProvider.sendRequest(invite);
        waitForMessage();
        receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
        if (receivedRequestEvent == null || receivedRequestEvent.getRequest() == null)
          throw new TiUnexpectedError("The sent request was not received by the RI!");
      } catch (TooManyListenersException ex) {
        throw new TiUnexpectedError(
            "A TooManyListenersException was thrown while trying to add "
                + "a SipListener to a TI SipProvider.",
            ex);
      } catch (SipException ex) {
        throw new TckInternalError("The RI failed to send the request!", ex);
      }
      Request receivedRequest = receivedRequestEvent.getRequest();
      // 2. Create and send the response
      // Create an ok response. We are not testing the message factory so let's
      // not leave it a chance to mess something up and specify the response
      // as completely as possible.
      List via = new LinkedList();
      via.add(receivedRequest.getHeader(ViaHeader.NAME));
      Response ok = null;
      try {
        ok =
            tiMessageFactory.createResponse(
                Response.OK,
                (CallIdHeader) receivedRequest.getHeader(CallIdHeader.NAME),
                (CSeqHeader) receivedRequest.getHeader(CSeqHeader.NAME),
                (FromHeader) receivedRequest.getHeader(FromHeader.NAME),
                (ToHeader) receivedRequest.getHeader(ToHeader.NAME),
                via,
                (MaxForwardsHeader) receivedRequest.getHeader(MaxForwardsHeader.NAME));
        addStatus(receivedRequest, ok);
      } catch (ParseException ex) {
        throw new TiUnexpectedError("Failed to create an OK response!", ex);
      }
      // Send the response using the TI and collect using RI
      try {
        eventCollector.collectResponseEvent(riSipProvider);
      } catch (TooManyListenersException ex) {
        throw new TckInternalError("Error while trying to add riSipProvider");
      }
      try {
        tiSipProvider.sendResponse(ok);
      } catch (SipException ex) {
        ex.printStackTrace();
        fail("A SipException occurred while trying to send an ok response.");
      }
      waitForMessage();
      ResponseEvent responseEvent = eventCollector.extractCollectedResponseEvent();
      assertNotNull("The sent response was not received by the RI!", responseEvent);
      assertNotNull("The sent response was not received by the RI!", responseEvent.getResponse());
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }
    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
Example #15
0
  // Information needed to get a single file:
  // BASE_PATH, FILE_ID, TIMESTAMP_START, TIMESTAMP_STOP, SOURCE, FILESYSTEM
  private static Vector<Path> getFile(
      FileSystem fs, Hashtable<String, String> config, dbutil db_util) throws Exception {
    Long latestVersion = latestVersion(config, db_util);

    try {
      config.put("timestamp_start", config.get("timestamp_start"));
      config.put("timestamp_real", latestVersion.toString());
      config.put("timestamp_stop", latestVersion.toString());
    } catch (Exception E) {
      logger.error("Tryign to get file that is impossible to generate: " + getFullPath(config));
      return null;
    }
    if (Integer.parseInt(config.get("timestamp_start"))
        > Integer.parseInt(config.get("timestamp_stop"))) {
      return null;
    }
    logger.debug(
        "Getting DB for timestamp "
            + config.get("timestamp_start")
            + " to "
            + config.get("timestamp_stop"));

    String final_result = getFullPath(config);

    String temp_path_base =
        config.get("local_temp_path")
            + "_"
            + config.get("task_id")
            + "_"
            + config.get("run_id")
            + "/";
    Path newPath = new Path(final_result + "*");
    Vector<Path> ret_path = new Vector<Path>();
    String lockName = lock(final_result.replaceAll("/", "_"));
    if (fs.globStatus(newPath).length != 0) {
      ret_path.add(newPath);
      unlock(lockName);
      config.put("full_file_name", final_result);
      return ret_path;
    } else {
      if (!config.get("source").equals("local")) {
        config.put("temp_path_base", temp_path_base);

        config.put("timestamp_start", config.get("timestamp_start"));
        config.put("timestamp_real", latestVersion.toString());
        config.put("timestamp_stop", latestVersion.toString());

        Class<?> sourceClass =
            Class.forName("org.gestore.plugin.source." + config.get("source") + "Source");
        Method process_data = sourceClass.getMethod("process", Hashtable.class, FileSystem.class);
        Object processor = sourceClass.newInstance();
        Object retVal;
        try {
          retVal = process_data.invoke(processor, config, fs);
        } catch (InvocationTargetException E) {
          Throwable exception = E.getTargetException();
          logger.error("Unable to call method in child class: " + exception.toString());
          exception.printStackTrace(System.out);
          unlock(lockName);
          return null;
        }
        FileStatus[] files = (FileStatus[]) retVal;
        if (files == null) {
          logger.error("Error getting files, no files returned");
          return null;
        }

        for (FileStatus file : files) {
          Path cur_file = file.getPath();
          Path cur_local_path = new Path(temp_path_base + config.get("file_id"));
          String suffix = getSuffix(config.get("file_id"), cur_file.getName());
          cur_local_path = cur_local_path.suffix(suffix);
          Path res_path = new Path(new String(final_result + suffix));
          logger.debug("Moving file" + cur_file.toString() + " to " + res_path.toString());
          if (config.get("copy").equals("true")) {
            fs.moveFromLocalFile(cur_file, res_path);
          } else {
            fs.rename(cur_file, res_path);
          }
        }

        config.put("full_file_name", final_result);
      }
    }
    unlock(lockName);
    return ret_path;
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    System.out.println("called eventGroupUpload");
    response.setContentType("application/json");
    response.setHeader("Access-Control-Allow-Origin", "*");
    PrintWriter out = response.getWriter();
    JSONObject obj = new JSONObject();
    ArrayList<String> data = new ArrayList<String>();
    String appId = request.getParameter("appId");
    String name = request.getParameter("name");
    String imgUrl = request.getParameter("imgUrl");
    String about = request.getParameter("about");
    String rules = request.getParameter("rules");
    String contact = request.getParameter("contact");
    String callback = request.getParameter("callback");
    String responseType = request.getParameter("responseType");

    accessToken token = new accessToken();
    String accessToken = request.getParameter("accessToken");
    if ((accessToken != null) && token.get(accessToken)) {
      if (appId == null) {
        data.add("appId");
      }
      if (name == null) {
        data.add("name");
      }
      if (imgUrl == null) {
        data.add("imgUrl");
      }
      if (about == null) {
        data.add("about");
      }
      if (rules == null) {
        data.add("rules");
      }
      if (contact == null) {
        data.add("contact");
      }
      if (data.size() != 0) {
        obj.put("response", "error");
        obj.put("responseString", "Insufficient Data");
        obj.put("data", data);
      } else {

        try {
          beanEventGroupUpload bean = new beanEventGroupUpload();
          bean.setAppId(appId);
          bean.setName(name);
          bean.setImgUrl(imgUrl);
          bean.setAbout(about);
          bean.setRules(rules);
          bean.setContact(contact);
          daoEventGroupUpload dao = new daoEventGroupUpload();
          bean = dao.create(bean);
          if (bean.getValid()) {
            obj.put("response", "success");
            obj.put("responseString", "event uploaded successfully");
          } else {
            System.out.println("I am here");
            obj.put("response", "error");
            obj.put("responseString", bean.getException());
          }
        } catch (Throwable theException) {
          System.out.println("I am here1");
          obj.put("response", "error");
          obj.put("responseString", theException.toString());
        }
      }
    } else {
      obj.put("response", "error");
      obj.put("responseString", "Session expired");
    }
    if (responseType.equals("jsonp")) out.print(callback + "(" + obj + ")");
    else out.print(obj);
  }