@Test
 public void testGenTypeCreateTypeLibraryLibVersionInvalidValueStr() {
   ServiceGenerator sGenerator = new ServiceGenerator();
   String[] pluginParameter = {
     "-gentype",
     "genTypeCreateTypeLibrary",
     "-pr",
     PROJECT_ROOT_CATEGORY,
     "-libname",
     "CategoryTypeLibrary",
     "-libVersion",
     "a.b.c",
     "-libNamespace",
     "http://www.ebayopensource.org/soaframework/examples/config"
   };
   try {
     sGenerator.startCodeGen(pluginParameter);
   } catch (Exception e) {
     e.printStackTrace();
     String exceptionClass =
         "org.ebayopensource.turmeric.tools.codegen.exception.BadInputValueException";
     String exceptionMessage =
         "The Library version should be in the format X.Y.Z where X,Y and Z are integers.";
     assertTrue(
         "Expected Exception message:"
             + exceptionMessage
             + " || Actual Exception message:"
             + e.getMessage(),
         e.getMessage().contains(exceptionMessage));
     assertTrue(
         "Expected Exception Class:" + exceptionClass + ", Actual:" + e.getClass().getName(),
         e.getClass().getName().equals(exceptionClass));
   }
 }
  @Override
  protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    try {
      if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {
        updateFolder(actionRequest);
      } else if (cmd.equals(Constants.DELETE)) {
        deleteFolders(actionRequest, false);
      } else if (cmd.equals(Constants.MOVE_TO_TRASH)) {
        deleteFolders(actionRequest, true);
      } else if (cmd.equals(Constants.RESTORE)) {
        restoreTrashEntries(actionRequest);
      } else if (cmd.equals(Constants.SUBSCRIBE)) {
        subscribeFolder(actionRequest);
      } else if (cmd.equals(Constants.UNSUBSCRIBE)) {
        unsubscribeFolder(actionRequest);
      }
    } catch (Exception e) {
      if (e instanceof NoSuchFolderException || e instanceof PrincipalException) {

        SessionErrors.add(actionRequest, e.getClass());

        actionResponse.setRenderParameter("mvcPath", "/bookmarks/error.jsp");
      } else if (e instanceof FolderNameException) {
        SessionErrors.add(actionRequest, e.getClass());
      } else {
        throw e;
      }
    }
  }
Ejemplo n.º 3
0
 @WebMethod
 @Path("/setAssignmentAcceptUntil")
 @Produces("text/plain")
 @GET
 public String setAssignmentAcceptUntil(
     @WebParam(name = "sessionId", partName = "sessionId") @QueryParam("sessionId")
         String sessionId,
     @WebParam(name = "assignmentId", partName = "assignmentId") @QueryParam("assignmentId")
         String assignmentId) {
   LOG.info("setting accept until time for assignment: " + assignmentId);
   try {
     Session s = establishSession(sessionId);
     AssignmentEdit assignment = assignmentService.editAssignment(assignmentId);
     LOG.debug("got assignment: " + assignment.getTitle());
     LOG.debug("assignment closes: " + assignment.getDueTime());
     assignment.setCloseTime(assignment.getDueTime());
     assignmentService.commitEdit(assignment);
     LOG.debug("edit committed");
   } catch (Exception e) {
     LOG.error(
         "WS setAssignmentAcceptUntil(): " + e.getClass().getName() + " : " + e.getMessage());
     return e.getClass().getName() + " : " + e.getMessage();
   }
   return "success";
 }
  @Override
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    try {
      updateInstance(actionRequest);

      sendRedirect(actionRequest, actionResponse);
    } catch (Exception e) {
      if (e instanceof NoSuchCompanyException || e instanceof PrincipalException) {

        SessionErrors.add(actionRequest, e.getClass().getName());

        setForward(actionRequest, "portlet.admin.error");
      } else if (e instanceof CompanyMxException
          || e instanceof CompanyVirtualHostException
          || e instanceof CompanyWebIdException) {

        SessionErrors.add(actionRequest, e.getClass().getName());
      } else {
        throw e;
      }
    }
  }
  @Test
  public void testSimpleCircuitBreakerGroupBlocking() {

    Exception exception = null;
    try {
      callExternalResource1GroupA(true);
    } catch (Exception ignore) {
      exception = ignore;
    }
    Assert.assertEquals(MyException.class, exception.getClass());

    exception = null;

    try {
      callExternalResource2GroupA(true);
    } catch (Exception ignore) {
      exception = ignore;
    }
    Assert.assertEquals(MyException.class, exception.getClass());

    // next call shall be blocked by CB.
    try {
      callExternalResource1GroupA(true);
    } catch (MyException e) {
      Assert.fail("MyException not expected here");
    }
  }
Ejemplo n.º 6
0
  /** Test method for {@link it.reexon.lib.date.DateUtils#average(it.reexon.lib.date.DateRange)}. */
  @Test
  public final void testAverageDateRange() {
    try {
      DateRange dateRange = new DateRange(date01, date05);
      Date averageDate = DateUtils.average(dateRange);
      Assert.assertEquals(date03.getTime(), averageDate.getTime());

      try {
        dateRange.setDateFrom(null);
        DateUtils.average(Collections.emptyList());
        Assert.fail("Should have thrown an exception");
      } catch (Exception e) {
        Assert.assertEquals(e.getClass(), IllegalArgumentException.class);
      }
      try {
        dateRange.setDateFrom(null);
        dateRange.setDateTo(null);
        DateUtils.average(Collections.emptyList());
        Assert.fail("Should have thrown an exception");
      } catch (Exception e) {
        Assert.assertEquals(e.getClass(), IllegalArgumentException.class);
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 7
0
  /**
   * Test method for {@link it.reexon.lib.date.DateUtils#between(java.util.Date, java.util.Date,
   * java.util.Date)}.
   */
  @Test
  public final void testBetween() {
    try {
      Boolean between = DateUtils.between(date05, date01, date10);
      Assert.assertTrue(between);

      between = DateUtils.between(date01, date05, date10);
      Assert.assertFalse(between);

      try {
        DateUtils.between(date05, null, date10);
        Assert.fail("Should have thrown an exception");
      } catch (Exception e) {
        Assert.assertEquals(e.getClass(), IllegalArgumentException.class);
      }
      try {
        DateUtils.between(null, null, null);
        Assert.fail("Should have thrown an exception");
      } catch (Exception e) {
        Assert.assertEquals(e.getClass(), IllegalArgumentException.class);
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e);
    }
  }
  public ModelAndView handleException(Exception exception, String generalMessageKey) {
    ReturnMessage message = null;

    boolean logRequired = true;

    if (ServiceRunTimeException.class.isAssignableFrom(exception.getClass())) {
      message = handleException((ServiceRunTimeException) exception);
    } else if (ServiceException.class.isAssignableFrom(exception.getClass())) {
      message = handleException((ServiceException) exception);
    } else if (UniqueConstraintsException.class.isAssignableFrom(exception.getClass())) {
      message = handleException((UniqueConstraintsException) exception);
      // This is just a validation message do not log.
      logRequired = false;
    } else {
      message =
          getError(
              getMessages()
                  .getMessage(
                      GeneralProperties.class.getName()
                          + "."
                          + GeneralProperties.ERROR_TITLE.name()),
              getMessages().getMessage(generalMessageKey, getModelName()));
    }

    if (logRequired) {
      logger.error(exception.getMessage());

      if (logger.isDebugEnabled()) {
        logger.debug("ERROR - " + exception.getMessage(), exception);
      }
    }

    return getXMLViewer(message);
  }
  @Override
  public void processAction(
      ActionMapping actionMapping,
      ActionForm actionForm,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    try {
      if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {
        updateAction(actionRequest);
      } else if (cmd.equals(Constants.DELETE)) {
        deleteActions(actionRequest);
      }

      sendRedirect(actionRequest, actionResponse);
    } catch (Exception e) {
      if (e instanceof PrincipalException) {
        SessionErrors.add(actionRequest, e.getClass());

        setForward(actionRequest, "portlet.mobile_device_rules.error");
      } else if (e instanceof ActionTypeException
          || e instanceof NoSuchActionException
          || e instanceof NoSuchRuleGroupException) {

        SessionErrors.add(actionRequest, e.getClass());
      } else {
        throw e;
      }
    }
  }
  @Override
  protected void doProcessCommand(PortletRequest portletRequest, PortletResponse portletResponse)
      throws Exception {

    try {
      copyArticle(portletRequest);
    } catch (Exception e) {
      if (e instanceof NoSuchArticleException || e instanceof PrincipalException) {

        SessionErrors.add(portletRequest, e.getClass());

        PortletSession portletSession = portletRequest.getPortletSession();

        PortletContext portletContext = portletSession.getPortletContext();

        PortletRequestDispatcher portletRequestDispatcher =
            portletContext.getRequestDispatcher("/html/portlet/journal/error.jsp");

        portletRequestDispatcher.include(portletRequest, portletResponse);
      } else if (e instanceof DuplicateArticleIdException || e instanceof ArticleIdException) {

        SessionErrors.add(portletRequest, e.getClass());
      } else {
        throw e;
      }
    }
  }
Ejemplo n.º 11
0
  /**
   * Calculates the largest ID int in the database and returns it.
   *
   * @return - returns the largest ID int in the database
   */
  private int getMaxQuestionID() {
    if (maxQuestionID != null) {
      return maxQuestionID;
    } else {
      try {
        Class.forName("org.sqlite.JDBC");
      } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
      }

      try (Connection connection =
          DriverManager.getConnection("jdbc:sqlite:src/mazeDB/mazeQuestions.db"); ) {
        connection.setAutoCommit(false);
        try (Statement statement = connection.createStatement();
            ResultSet idResultSet = statement.executeQuery("SELECT max(ID) FROM QUESTION;"); ) {
          if (idResultSet.next()) {
            maxQuestionID = idResultSet.getInt(1);
          } else {
            throw new RuntimeException("Error attempting to query max QUESTION ID");
          }
        }
      } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
      }
    }
    return maxQuestionID;
  }
Ejemplo n.º 12
0
  @Override
  public void processAction(
      ActionMapping actionMapping,
      ActionForm actionForm,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    try {
      if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {
        updateLicense(actionRequest);
      } else if (cmd.equals(Constants.DELETE)) {
        deleteLicense(actionRequest);
      }

      sendRedirect(actionRequest, actionResponse);
    } catch (Exception e) {
      if (e instanceof NoSuchLicenseException || e instanceof PrincipalException) {

        SessionErrors.add(actionRequest, e.getClass());

        setForward(actionRequest, "portlet.software_catalog.error");
      } else if (e instanceof LicenseNameException || e instanceof RequiredLicenseException) {

        SessionErrors.add(actionRequest, e.getClass());
      } else {
        throw e;
      }
    }
  }
 @Test
 public void testGenTypeCreateTypeLibraryLibNameSpaceIsMissing() {
   ServiceGenerator sGenerator = new ServiceGenerator();
   String[] pluginParameter = {
     "-gentype",
     "genTypeCreateTypeLibrary",
     "-pr",
     PROJECT_ROOT_CATEGORY,
     "-libname",
     "CategoryTypeLibrary",
     "-libVersion",
     "1.2.3",
     "http://www.ebayopensource.org/soaframework/examples/config"
   };
   try {
     sGenerator.startCodeGen(pluginParameter);
   } catch (Exception e) {
     e.printStackTrace();
     String exceptionClass =
         "org.ebayopensource.turmeric.tools.codegen.exception.BadInputOptionException";
     String exceptionMessage =
         "Invalid option http://www.ebayopensource.org/soaframework/examples/config specified. This option is not recognized.";
     assertTrue(
         "Expected Exception message:"
             + exceptionMessage
             + " || Actual Exception message:"
             + e.getMessage(),
         e.getMessage().contains(exceptionMessage));
     assertTrue(
         "Expected Exception Class:" + exceptionClass + ", Actual:" + e.getClass().getName(),
         e.getClass().getName().equals(exceptionClass));
   }
 }
 /**
  * Determine the view name for the given exception, first checking against the {@link
  * #setExcludedExceptions(Class[]) "excludedExecptions"}, then searching the {@link
  * #setExceptionMappings "exceptionMappings"}, and finally using the {@link #setDefaultErrorView
  * "defaultErrorView"} as a fallback.
  *
  * @param ex the exception that got thrown during handler execution
  * @param request current HTTP request (useful for obtaining metadata)
  * @return the resolved view name, or {@code null} if excluded or none found
  */
 protected String determineViewName(Exception ex, HttpServletRequest request) {
   String viewName = null;
   if (this.excludedExceptions != null) {
     for (Class<?> excludedEx : this.excludedExceptions) {
       if (excludedEx.equals(ex.getClass())) {
         return null;
       }
     }
   }
   // Check for specific exception mappings.
   if (this.exceptionMappings != null) {
     viewName = findMatchingViewName(this.exceptionMappings, ex);
   }
   // Return default error view else, if defined.
   if (viewName == null && this.defaultErrorView != null) {
     if (logger.isDebugEnabled()) {
       logger.debug(
           "Resolving to default view '"
               + this.defaultErrorView
               + "' for exception of type ["
               + ex.getClass().getName()
               + "]");
     }
     viewName = this.defaultErrorView;
   }
   return viewName;
 }
  public Object CallTransfer(String URL, String NAMESPACE, String METHOD_NAME, String SOAP_ACTION) {

    try {
      // o=new Object();
      SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

      request.addProperty("sender", IMSI);
      request.addProperty("msgstr", MSGSTR);

      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
      envelope.setOutputSoapObject(request);
      HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
      androidHttpTransport.call(SOAP_ACTION, envelope);
      // response = (Object) envelope.bodyIn;
      response = envelope.getResponse();
    } catch (Exception E) {
      E.printStackTrace();
      System.out.print("ERROR" + E.getClass().getName() + E.getMessage());
      Toast.makeText(
          null,
          "ERROR" + E.getClass().getName() + "here exp frm ws" + E.getMessage(),
          Toast.LENGTH_LONG);
    }
    return response;
  }
 @Test
 public void testGenTypeCreateTypeLibraryLibNameSpaceValueEmptyString() {
   ServiceGenerator sGenerator = new ServiceGenerator();
   String[] pluginParameter = {
     "-gentype",
     "genTypeCreateTypeLibrary",
     "-pr",
     PROJECT_ROOT_CATEGORY,
     "-libname",
     "CategoryTypeLibrary",
     "-libVersion",
     "1.2.3",
     "-libNamespace",
     ""
   };
   try {
     sGenerator.startCodeGen(pluginParameter);
   } catch (Exception e) {
     e.printStackTrace();
     String exceptionClass =
         "org.ebayopensource.turmeric.tools.codegen.exception.BadInputValueException";
     String exceptionMessage = "Please provide a proper value for the option -libnamespace";
     assertTrue(
         "Expected Exception message:"
             + exceptionMessage
             + " || Actual Exception message:"
             + e.getMessage(),
         e.getMessage().contains(exceptionMessage));
     assertTrue(
         "Expected Exception Class:" + exceptionClass + ", Actual:" + e.getClass().getName(),
         e.getClass().getName().equals(exceptionClass));
   }
 }
Ejemplo n.º 17
0
 /** Convert an exception object to a Json string. */
 public static String toJsonString(final Exception e) {
   final Map<String, Object> m = new TreeMap<String, Object>();
   m.put("exception", e.getClass().getSimpleName());
   m.put("message", e.getMessage());
   m.put("javaClassName", e.getClass().getName());
   return toJsonString(RemoteException.class, m);
 }
 @Test
 public void testGenTypeCreateTypeLibraryPrIsMissing() {
   ServiceGenerator sGenerator = new ServiceGenerator();
   String[] pluginParameter = {
     "-gentype",
     "genTypeCreateTypeLibrary",
     "-libname",
     "CategoryTypeLibrary",
     "-libVersion",
     "1.2.3",
     "-libNamespace",
     "http://www.ebayopensource.org/soaframework/examples/config"
   };
   try {
     sGenerator.startCodeGen(pluginParameter);
   } catch (Exception e) {
     e.printStackTrace();
     String exceptionClass =
         "org.ebayopensource.turmeric.tools.codegen.exception.MissingInputOptionException";
     String exceptionMessage = "Project Root is missing.";
     assertTrue(
         "Expected Exception message:"
             + exceptionMessage
             + " || Actual Exception message:"
             + e.getMessage(),
         e.getMessage().contains(exceptionMessage));
     assertTrue(
         "Expected Exception Class:" + exceptionClass + ", Actual:" + e.getClass().getName(),
         e.getClass().getName().equals(exceptionClass));
   }
 }
Ejemplo n.º 19
0
  /**
   * Ask our exception handler to handle the exception. Return the <code>ActionForward</code>
   * instance (if any) returned by the called <code>ExceptionHandler</code>.
   *
   * @param request The servlet request we are processing
   * @param response The servlet response we are processing
   * @param exception The exception being handled
   * @param form The ActionForm we are processing
   * @param mapping The ActionMapping we are using
   * @return The <code>ActionForward</code> instance (if any) returned by the called <code>
   *     ExceptionHandler</code>.
   * @throws IOException if an input/output error occurs
   * @throws ServletException if a servlet exception occurs
   */
  protected ActionForward processException(
      HttpServletRequest request,
      HttpServletResponse response,
      Exception exception,
      ActionForm form,
      ActionMapping mapping)
      throws IOException, ServletException {
    // Is there a defined handler for this exception?
    ExceptionConfig config = mapping.findException(exception.getClass());

    if (config == null) {
      log.warn(getInternal().getMessage("unhandledException", exception.getClass()));

      if (exception instanceof IOException) {
        throw (IOException) exception;
      } else if (exception instanceof ServletException) {
        throw (ServletException) exception;
      } else {
        throw new ServletException(exception);
      }
    }

    // Use the configured exception handling
    try {
      ExceptionHandler handler =
          (ExceptionHandler) RequestUtils.applicationInstance(config.getHandler());

      return (handler.execute(exception, config, mapping, form, request, response));
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
 @Override
 public EbuildleapResultObject getHomeUnitVersions(HomeUnit homeUnit) {
   try {
     ero.clear();
     /*
      * validate user input
      */
     if (homeUnit == null || homeUnit.getId() == null) {
       throw new Exception(
           ebuildLeapPropertiesUtil.getProperty(EbuildleapConstants.MISSING_HOMEUNIT_ID));
     }
     ArrayList<HomeUnitVersion> result = new ArrayList<HomeUnitVersion>();
     result.addAll(homeUnitVersionRepository.findByHomeUnit_Id(homeUnit.getId()));
     ero.setResultStatus(EbuildleapConstants.SERVICE_CALL_SUCCESSFUL);
     ero.setResult(result);
   } catch (Exception e) {
     log.debug(e.getClass() + ": " + e.getMessage(), e);
     e.printStackTrace();
     ero.setResultStatus(EbuildleapConstants.SERVICE_CALL_FAILED);
     ero.setErrCode(EbuildleapConstants.ERROR_RETRIEVING_HOMEUNIT_VERSIONS);
     ero.setErrDescription(
         ebuildLeapPropertiesUtil.getProperty(
                 EbuildleapConstants.ERROR_RETRIEVING_HOMEUNIT_VERSIONS)
             + " - "
             + e.getClass()
             + ": "
             + e.getMessage());
   }
   return ero;
 }
Ejemplo n.º 21
0
  /**
   * Parse an XML Catalog stream.
   *
   * @param catalog The catalog to which this catalog file belongs
   * @param is The input stream from which the catalog will be read
   * @throws MalformedURLException Improper fileUrl
   * @throws IOException Error reading catalog file
   * @throws CatalogException A Catalog exception
   */
  public void readCatalog(Catalog catalog, InputStream is) throws IOException, CatalogException {

    // Create an instance of the parser
    if (parserFactory == null && parserClass == null) {
      debug.message(1, "Cannot read SAX catalog without a parser");
      throw new CatalogException(CatalogException.UNPARSEABLE);
    }

    debug = catalog.getCatalogManager().debug;
    EntityResolver bResolver = catalog.getCatalogManager().getBootstrapResolver();

    this.catalog = catalog;

    try {
      if (parserFactory != null) {
        SAXParser parser = parserFactory.newSAXParser();
        SAXParserHandler spHandler = new SAXParserHandler();
        spHandler.setContentHandler(this);
        if (bResolver != null) {
          spHandler.setEntityResolver(bResolver);
        }
        parser.parse(new InputSource(is), spHandler);
      } else {
        Parser parser =
            (Parser)
                Class.forName(
                        parserClass,
                        true,
                        loader != null ? loader : this.getClass().getClassLoader())
                    .newInstance();
        parser.setDocumentHandler(this);
        if (bResolver != null) {
          parser.setEntityResolver(bResolver);
        }
        parser.parse(new InputSource(is));
      }
    } catch (ClassNotFoundException cnfe) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (IllegalAccessException iae) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (InstantiationException ie) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (ParserConfigurationException pce) {
      throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
    } catch (SAXException se) {
      Exception e = se.getException();
      // FIXME: there must be a better way
      UnknownHostException uhe = new UnknownHostException();
      FileNotFoundException fnfe = new FileNotFoundException();
      if (e != null) {
        if (e.getClass() == uhe.getClass()) {
          throw new CatalogException(CatalogException.PARSE_FAILED, e.toString());
        } else if (e.getClass() == fnfe.getClass()) {
          throw new CatalogException(CatalogException.PARSE_FAILED, e.toString());
        }
      }
      throw new CatalogException(se);
    }
  }
Ejemplo n.º 22
0
  @Override
  public void run() {
    try {
      // waiting until the data-sink was set from outside
      synchronized (this) {
        while (this.sink == null) this.wait();
      }

      // waiting for new commands
      while (!this.stopped && !Thread.interrupted()) {
        try {
          // fetch the next complete crawler document
          ICrawlerDocument crawlerDoc = execCompletionService.take().get();
          if (crawlerDoc != null && crawlerDoc.getStatus() == ICrawlerDocument.Status.OK) {

            // create a new ICommand
            final IDocumentFactory cmdFactory = this.docFactories.get(ICommand.class.getName());
            final ICommand cmd = cmdFactory.createDocument(ICommand.class);
            cmd.setLocation(crawlerDoc.getLocation());
            cmd.setProfileOID(this.getProfileID());
            cmd.setDepth(0);
            cmd.setResult(ICommand.Result.Passed, null);

            /* Sending event via command-tracker!
             *
             * Calling this function should also created a valid command OID for us
             */
            this.commandTracker.commandCreated(this.getClass().getName(), cmd);
            if (cmd.getOID() <= 0) {
              this.logger.warn(
                  String.format(
                      "Command with location '%s' has an invalid OID '%d'. ORM mapping seems not to work. Command is not enqueued.",
                      cmd.getLocation(), Integer.valueOf(cmd.getOID())));
            } else {
              cmd.setCrawlerDocument(crawlerDoc);

              // put it into the data-sink
              this.sink.putData(cmd);
            }
          }
        } catch (Exception e) {
          if (!(e instanceof InterruptedException)) {
            this.logger.error(
                String.format(
                    "%s: Unexpected '%s' while waiting for new commands to enqueue.",
                    this.getName(), e.getClass().getName()),
                e);
          } else {
            this.logger.info("Thread stopped successfully.");
            break;
          }
        }
      }
    } catch (Exception e) {
      this.logger.error(
          String.format("%s: Unexpected '%s'.", this.getName(), e.getClass().getName()), e);
    }
  }
  @Override
  public void processAction(
      ActionMapping actionMapping,
      ActionForm actionForm,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    try {
      if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {
        validateCAS(actionRequest);
        validateLDAP(actionRequest);

        if (!SessionErrors.isEmpty(actionRequest)) {
          setForward(actionRequest, "portlet.portal_settings.edit_company");
        } else {
          updateCompany(actionRequest);

          sendRedirect(actionRequest, actionResponse);
        }
      }
    } catch (Exception e) {
      if (e instanceof PrincipalException) {
        SessionErrors.add(actionRequest, e.getClass());

        setForward(actionRequest, "portlet.portal_settings.error");
      } else if (e instanceof AddressCityException
          || e instanceof AccountNameException
          || e instanceof AddressStreetException
          || e instanceof AddressZipException
          || e instanceof CompanyMxException
          || e instanceof CompanyVirtualHostException
          || e instanceof CompanyWebIdException
          || e instanceof EmailAddressException
          || e instanceof LocaleException
          || e instanceof NoSuchCountryException
          || e instanceof NoSuchListTypeException
          || e instanceof NoSuchRegionException
          || e instanceof PhoneNumberException
          || e instanceof WebsiteURLException) {

        if (e instanceof NoSuchListTypeException) {
          NoSuchListTypeException nslte = (NoSuchListTypeException) e;

          SessionErrors.add(actionRequest, e.getClass().getName() + nslte.getType());
        } else {
          SessionErrors.add(actionRequest, e.getClass(), e);
        }

        setForward(actionRequest, "portlet.portal_settings.edit_company");
      } else {
        throw e;
      }
    }
  }
Ejemplo n.º 24
0
  /**
   * Gets a question from the database not currently in the HashMap
   *
   * @return - a new question
   */
  private MazeQuestion getNewQuestion() {
    maxQuestionID = getMaxQuestionID();
    Random rng = new Random(System.currentTimeMillis() + System.nanoTime());
    int modValue = uniqueInstance.getMaxQuestionID() + 1;

    MazeQuestion newQuestion = null;

    while (newQuestion == null) {
      int toTry = rng.nextInt(modValue);

      if (questionHashMap.containsKey(new Integer(toTry))) {
        continue;
      }

      try {
        Class.forName("org.sqlite.JDBC");
      } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
      }

      try (Connection connection = DriverManager.getConnection(MazeDB.getDBPath()); ) {
        connection.setAutoCommit(false);
        try (Statement statement = connection.createStatement();
            ResultSet rs =
                statement.executeQuery("SELECT * FROM QUESTION WHERE ID = " + toTry + ";"); ) {
          if (rs.next()) {

            int newQuestionID = rs.getInt(1);
            char newQuestionType = rs.getString(2).charAt(0);
            char newFileType = rs.getString(3).charAt(0);
            String newQuestionText = rs.getString(4);
            String newAnswerText = rs.getString(5);
            String newFilePath = rs.getString(6);

            // unescape SQL '
            newQuestionText = newQuestionText.replaceAll("''", "'");

            newQuestion =
                new MazeQuestion(
                    newQuestionID,
                    newQuestionType,
                    newFileType,
                    newQuestionText,
                    newAnswerText,
                    newFilePath);

          } else {
            continue;
          }
        }
      } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
      }
    }
    return newQuestion;
  }
Ejemplo n.º 25
0
  @WebMethod
  @Path("/createSubmission")
  @Produces("text/plain")
  @GET
  public String createSubmission(
      @WebParam(name = "sessionId", partName = "sessionId") @QueryParam("sessionId")
          String sessionId,
      @WebParam(name = "context", partName = "context") @QueryParam("context") String context,
      @WebParam(name = "assignmentId", partName = "assignmentId") @QueryParam("assignmentId")
          String assignmentId,
      @WebParam(name = "userId", partName = "userId") @QueryParam("userId") String userId,
      @WebParam(name = "time", partName = "time") @QueryParam("time") long time) {
    LOG.info(
        "createSubmission( "
            + sessionId
            + ", "
            + context
            + " , "
            + assignmentId
            + " , "
            + userId
            + ","
            + time
            + ")");
    try {
      // establish the session
      Session s = establishSession(sessionId);
      Assignment assign = assignmentService.getAssignment(assignmentId);

      User user = userDirectoryService.getUserByEid(userId);
      if (user == null) {
        return "user does not exit";
      } else {
        LOG.info("Got user " + userId);
      }
      // s.setUserId(user.getId());
      // s.setUserEid(userId);

      AssignmentSubmissionEdit ase =
          assignmentService.addSubmission(
              context, assignmentId, userDirectoryService.getUserId(userId));

      ase.clearSubmitters();
      ase.addSubmitter(user);
      ase.setSubmitted(true);

      Time subTime = timeService.newTime(time);
      LOG.info("Setting time to " + time);
      ase.setTimeSubmitted(subTime);
      assignmentService.commitEdit(ase);
      return ase.getId();

    } catch (Exception e) {
      LOG.error("WS createSubmission(): " + e.getClass().getName() + " : " + e.getMessage());
      return e.getClass().getName() + " : " + e.getMessage();
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see
  * com.ebuild.leap.service.HomeUnitServiceFacade#getHomeUnitVersion(com.
  * ebuild.leap.pojo.HomeUnitVersion)
  *
  * Returns Latest HomeUnit Revision for the given HomeUnit Version
  */
 @Override
 public EbuildleapResultObject getLatestHomeUnitRevision(HomeUnitVersion homeUnitVersion) {
   log.debug("START ---- INSIDE HomeUnitServiceFacadeImpl - getLatestHomeUnitRevision");
   try {
     ero.clear();
     /*
      * validate user input
      */
     if (homeUnitVersion == null || homeUnitVersion.getId() == null) {
       throw new Exception(
           ebuildLeapPropertiesUtil.getProperty(EbuildleapConstants.MISSING_HOMEUNITVERSION_ID));
     }
     /*
      * STEP 1:- Pick the latest HomeUnit Revision for the HomeUnit
      * Version
      */
     HomeUnitRevision latestRevision =
         homeUnitRevisionRepository.getLatestRevisionId(homeUnitVersion.getId());
     if (latestRevision == null) {
       // NO REVISIONS FOR THE VERSION. SET ERROR and RETURN
       throw new DataRetrievalFailureException(
           ebuildLeapPropertiesUtil.getProperty(EbuildleapConstants.NO_REVISION_FOUND_FOR_VERSION)
               + " - "
               + homeUnitVersion.getId());
     }
     /*
      * STEP 2:- Pick the Home Unit Revision from NOSQL DB
      */
     HomeUnitRevision mongoLatestRevision =
         homeUnitRevisionMongoRepository.findOne(latestRevision.getId());
     if (mongoLatestRevision == null) {
       // Revision not found in MONGO - throw exception
       throw new DataRetrievalFailureException(
           ebuildLeapPropertiesUtil.getProperty(EbuildleapConstants.OBJECT_NOT_FOUND_IN_DATASTORE)
               + " - "
               + latestRevision.getId());
     }
     ArrayList<HomeUnitRevision> result = new ArrayList<HomeUnitRevision>();
     result.add(mongoLatestRevision);
     ero.setResultStatus(EbuildleapConstants.SERVICE_CALL_SUCCESSFUL);
     ero.setResult(result);
   } catch (Exception e) {
     log.debug(e.getClass() + ": " + e.getMessage(), e);
     e.printStackTrace();
     ero.setResultStatus(EbuildleapConstants.SERVICE_CALL_FAILED);
     ero.setErrCode(EbuildleapConstants.ERROR_RETRIEVING_LATEST_HOMEUNITREVISION);
     ero.setErrDescription(
         ebuildLeapPropertiesUtil.getProperty(
                 EbuildleapConstants.ERROR_RETRIEVING_LATEST_HOMEUNITREVISION)
             + " - "
             + e.getClass()
             + ": "
             + e.getMessage());
   }
   log.debug("END ---- INSIDE HomeUnitServiceFacadeImpl - getLatestHomeUnitRevision");
   return ero;
 }
  public LeadsIntermediateIterator(String key, String prefix, InfinispanManager imanager, int i) {
    log = LoggerFactory.getLogger(LeadsIntermediateIterator.class);
    this.imanager = imanager;
    // initialize cache
    intermediateDataCache = (Cache) imanager.getPersisentCache(prefix + ".data");
    indexSiteCache = (Cache) imanager.getPersisentCache(prefix + ".indexed");
    baseIntermKey = new ComplexIntermediateKey();
    baseIntermKey.setCounter(currentCounter);
    baseIntermKey.setKey(key);

    // read all the IndexComplexIntermediateKeys with attribute == keys
    this.list = new ArrayList<>();
    try {
      CloseableIterable<Map.Entry<String, Object>> myIterable =
          ((Cache) indexSiteCache)
              .getAdvancedCache()
              .filterEntries(new IndexedComplexIntermKeyFilter(key));
      for (Map.Entry<String, Object> entry : myIterable) {
        //        System.err.println("ADDING TO LIST key: " + entry.getKey() + " value " +
        // entry.getValue().toString());
        if (entry.getValue() instanceof IndexedComplexIntermediateKey) {
          ComplexIntermediateKey c =
              new ComplexIntermediateKey((IndexedComplexIntermediateKey) entry.getValue());
          list.add((IndexedComplexIntermediateKey) entry.getValue());
        } else {
          System.err.println("\n\nGET [B once again");
        }
      }
      // check if the number of iterations is correct //this constructor is for debugging purposes
      if (i != list.size()) {
        System.err.println(
            "iterator size "
                + key
                + " "
                + list.size()
                + " correct number: "
                + i
                + " size of cache with IndexedComplexIntermediateKey "
                + indexSiteCache.size());
      }
    } catch (Exception e) {
      System.err.println("Exception on LeadsIntermediateIterator " + e.getClass().toString());
      System.err.println("Message: " + e.getMessage());
      log.error("Exception on LeadsIntermediateIterator " + e.getClass().toString());
      log.error("Message: " + e.getMessage());
    }

    chunkIterator = list.iterator();

    if (chunkIterator.hasNext()) {
      currentChunk = chunkIterator.next();
      baseIntermKey = new ComplexIntermediateKey(currentChunk);
    } else {
      currentChunk = null;
    }
  }
 public Integer findCode(Exception exception) throws Exception {
   Integer code = null;
   HttpStatus status = AnnotationUtils.findAnnotation(exception.getClass(), HttpStatus.class);
   if (status != null) {
     code = status.value().getStatusCode();
   } else if (exception.getClass().equals(NotFoundException.class)) {
     code = Response.Status.NOT_FOUND.getStatusCode();
   }
   return code;
 }
 public ServiceResponse<Void> disposeContainer(String containerId) {
   try {
     KieContainerInstance kci = (KieContainerInstance) context.removeContainer(containerId);
     if (kci != null) {
       synchronized (kci) {
         kci.setStatus(KieContainerStatus.DISPOSING); // just in case
         if (kci.getKieContainer() != null) {
           InternalKieContainer kieContainer = kci.getKieContainer();
           kci.setKieContainer(null); // helps reduce concurrent access issues
           try {
             // this may fail, but we already removed the container from the registry
             kieContainer.dispose();
           } catch (Exception e) {
             logger.warn(
                 "Container '"
                     + containerId
                     + "' disposed, but an unnexpected exception was raised",
                 e);
             return new ServiceResponse<Void>(
                 ServiceResponse.ResponseType.SUCCESS,
                 "Container "
                     + containerId
                     + " disposed, but exception was raised: "
                     + e.getClass().getName()
                     + ": "
                     + e.getMessage());
           }
           return new ServiceResponse<Void>(
               ServiceResponse.ResponseType.SUCCESS,
               "Container " + containerId + " successfully disposed.");
         } else {
           return new ServiceResponse<Void>(
               ServiceResponse.ResponseType.SUCCESS,
               "Container " + containerId + " was not instantiated.");
         }
       }
     } else {
       return new ServiceResponse<Void>(
           ServiceResponse.ResponseType.SUCCESS,
           "Container " + containerId + " was not instantiated.");
     }
   } catch (Exception e) {
     logger.error("Error disposing Container '" + containerId + "'", e);
     return new ServiceResponse<Void>(
         ServiceResponse.ResponseType.FAILURE,
         "Error disposing container "
             + containerId
             + ": "
             + e.getClass().getName()
             + ": "
             + e.getMessage());
   }
 }
Ejemplo n.º 30
0
 public void unhandledException(Exception e) {
   FlexoLoggingHandler flexoLoggingHandler = getFlexoLoggingHandler();
   if (flexoLoggingHandler != null) {
     flexoLoggingHandler.publishUnhandledException(
         new java.util.logging.LogRecord(
             java.util.logging.Level.WARNING,
             "Unhandled exception occured: " + e.getClass().getName()),
         e);
   } else {
     warning("Unexpected exception occured: " + e.getClass().getName());
   }
 }