@Override
  public void afterCompletion(
      HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
    if (ex == null) {
      return;
    }

    if (excludedExceptions.contains(ex.getClass())) {
      return;
    }
    for (Class<? extends Exception> excludedException : excludedExceptions) {
      if (excludedException.isInstance(ex)) {
        return;
      }
    }

    if (handler instanceof HandlerMethod) {
      HandlerMethod handlerMethod = (HandlerMethod) handler;
      Logger controllerLogger = Logger.getLogger(handlerMethod.getBeanType());
      controllerLogger.error(String.format("uncaught exception from %s", handlerMethod), ex);
    } else {
      logger.error(
          String.format("uncaught exception from a handler of unknown type: %s", handler), ex);
    }
  }
示例#2
0
 /** @see org.ow2.proactive.scheduler.common.task.TaskResult#value() */
 public Serializable value() throws Throwable {
   if (hadException()) {
     Throwable thrown = null;
     try {
       thrown = this.instanciateException(this.getTaskClassLoader());
     } catch (IOException e) {
       throw new InternalSchedulerException(
           "Cannot instanciate exception thrown by the task " + this.id + " : " + e.getMessage(),
           e);
     } catch (ClassNotFoundException e) {
       throw new InternalSchedulerException(
           "Cannot instanciate exception thrown by the task " + this.id + " : " + e.getMessage(),
           e);
     }
     throw thrown;
   } else {
     try {
       return this.instanciateValue(this.getTaskClassLoader());
     } catch (IOException e) {
       logger.error("", e);
       throw new InternalSchedulerException(
           "Cannot instanciate result of the task " + this.id + " : " + e.getMessage(), e);
     } catch (ClassNotFoundException e) {
       logger.error("", e);
       throw new InternalSchedulerException(
           "Cannot instanciate result of the task " + this.id + " : " + e.getMessage(), e);
     }
   }
 }
示例#3
0
  protected Iterable<ModelRoot> loadRoots() {
    ModuleDescriptor descriptor = getModuleDescriptor();
    if (descriptor == null) {
      return Collections.emptyList();
    }

    List<ModelRoot> result = new ArrayList<ModelRoot>();
    for (ModelRootDescriptor modelRoot : descriptor.getModelRootDescriptors()) {
      try {
        ModelRootFactory modelRootFactory =
            PersistenceFacade.getInstance().getModelRootFactory(modelRoot.getType());
        if (modelRootFactory == null) {
          LOG.error(
              "Unknown model root type: `" + modelRoot.getType() + "'. Requested by: " + this);
          continue;
        }

        ModelRoot root = modelRootFactory.create();
        Memento mementoWithFS = new MementoWithFS(modelRoot.getMemento(), myFileSystem);
        root.load(mementoWithFS);
        result.add(root);
      } catch (Exception e) {
        LOG.error(
            "Error loading models from root with type: `"
                + modelRoot.getType()
                + "'. Requested by: "
                + this,
            e);
      }
    }
    return result;
  }
示例#4
0
 public void init(List serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) {
   System.setProperty("java.io.tmpdir", serverConfig.getCachedir());
   try {
     this.serviceList = serviceList;
     this.serverConfig = serverConfig;
     this.mbeanServer = mbeanServer;
     fsManager.init();
   } catch (Exception e) {
     log.error("Unable to initialie file system: " + fsManager, e);
   }
   try {
     registry = LocateRegistry.createRegistry(Integer.parseInt(serverConfig.getRmiregistryport()));
     ic = new InitialContext();
     Context subctx = null;
     try {
       subctx = (Context) ic.lookup("java:");
     } catch (Exception ex) {
       log.error("initializing the java context", ex);
       // ex.printStackTrace();
     }
     if (subctx == null) {
       ic.createSubcontext("java:");
     }
     remoteBindingInterface = new RemoteBindingObject(ic);
     Object jndilookupobj =
         UnicastRemoteObject.exportObject(
             remoteBindingInterface, Integer.parseInt(serverConfig.getRmiregistryport()));
     registry.rebind("RemoteBindingObject", (Remote) jndilookupobj);
   } catch (Exception ex) {
     log.error("error in registring to the remote binding object", ex);
     // e1.printStackTrace();
   }
   log.info("initialized");
 }
示例#5
0
  public void applySettingStatusReport(JSONObject js) {
    /**
     * This breaks the mold a bit.. but its more efficient. This gets called off the top of
     * ParseJson if it has an "SR" in it. Sr's are called so often that instead of walking the
     * normal parsing tree.. this skips to the end
     */
    try {
      Iterator ii = js.keySet().iterator();
      // This is a special multi single value response object
      while (ii.hasNext()) {
        String key = ii.next().toString();

        responseCommand rc =
            new responseCommand(MNEMONIC_GROUP_SYSTEM, key.toString(), js.get(key).toString());
        TinygDriver.getInstance().machine.applyJsonStatusReport(rc);
        //                _applySettings(rc.buildJsonObject(), rc.getSettingParent()); //we will
        // supply the parent object name for each key pair
      }
      setChanged();
      message[0] = "STATUS_REPORT";
      message[1] = null;
      notifyObservers(message);

    } catch (Exception ex) {
      logger.error("[!] Error in applySettingStatusReport(JsonOBject js) : " + ex.getMessage());
      logger.error("[!]js.tostring " + js.toString());
      setChanged();
      message[0] = "STATUS_REPORT";
      message[1] = null;
      notifyObservers(message);
    }
  }
  public static void Update(Unlocked p) throws ResponseException {
    PreparedStatement statement = null;
    String query =
        "Update unlocked SET fk_profile_id=?,bonus_info=?,content_info=? where fk_profile_id=?;";
    Connection connect = null;
    IConnection c = MiscUtil.getIConnection();

    try {
      connect = c.init();
      statement = connect.prepareStatement(query);
      statement.setLong(1, p.getProfileId());
      statement.setString(2, p.getBonusInfo());
      statement.setString(3, p.getContentInfo());
      statement.setLong(4, p.getProfileId());
      statement.executeUpdate();
    } catch (SQLException e) {
      logger.error("SQL Error", e);
      throw new ResponseException("SQL Error", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (ResponseException e) {
      throw e;
    } finally {
      try {
        if (statement != null) statement.close();
        if (connect != null) connect.close();
      } catch (SQLException e) {
        logger.error("SQL Error", e);
      }
    }
  }
  /** This convenience method is set aside for readability. */
  private void getHibernateSession() {
    // import org.jboss.jpa.tx.TransactionScopedEntityManager;

    // Find a method for getting a hibernate session.
    Method[] emMethods = em.getClass().getMethods();
    for (Method method : emMethods) {
      if (method.getName().equals("getHibernateSession")) {
        // Once found, invoke the method.
        try {
          Object returnObj = method.invoke(em);
          if (returnObj instanceof Session) {
            session = (Session) returnObj;
          } else {
            logger.warn(
                "Invoking 'getHibernateSession()' returned type of "
                    + returnObj.getClass().getName()
                    + " instead of a hibernate session.");
          }
        } catch (Exception ex) {
          logger.error(
              "Failed to invoke the getter to obtain the hibernate session " + ex.getMessage());
          ex.printStackTrace();
        }
      }
    }

    if (session == null) {
      logger.error("Failed to find hibernate session from " + em.toString());
    }
  }
 @Override
 public List<AssessmentItem> getAssessmentItemByTypeId(Integer assessmentItemTypeId)
     throws ServerErrorException {
   if (assessmentItemTypeId == null || assessmentItemTypeId <= 0) {
     logger.error(LogConstants.objectIsNULLOrEmpty("Assessment Item Type Id"));
     throw new ServerErrorException(ErrorCodeConstants.SERVER_VALIDATION_ERROR);
   }
   List<AssessmentItem> assessmentItemsTemp = null;
   try {
     assessmentItemsTemp = assessmentItemDao.getAssessmentItemByTypeId(assessmentItemTypeId);
   } catch (Exception e) {
     logger.error(
         LogConstants.exceptionMessage(
             "Get assessment item by type[#" + assessmentItemTypeId + "]"),
         e);
     throw new ServerErrorException(ErrorCodeConstants.SERVER_ERROR);
   }
   if (assessmentItemsTemp == null) {
     logger.error(
         LogConstants.pureMessage(
             "Find assessment items by type[#" + assessmentItemTypeId + "] fail."));
     throw new ServerErrorException(ErrorCodeConstants.SERVER_VALIDATION_ERROR);
   }
   return assessmentItemsTemp;
 }
  public static void writeComplete(String filename, InterestPointListInfo ipl) {

    ObjectOutputStream out = null;
    try {
      out = new ObjectOutputStream(new FileOutputStream(filename));
      List<SURFInterestPoint> list = ipl.getList();
      out.writeInt(list.size());
      for (SURFInterestPoint ip : list) {
        out.writeObject(ip);
      }
      out.writeInt(ipl.getWidth());
      out.writeInt(ipl.getHeight());
      out.flush();
    } catch (Exception e) {
      logger.error(e.getMessage());
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
          logger.error(e.getMessage());
        }
      }
    }
  }
示例#10
0
  @Scheduled(fixedDelay = 10 * 60 * 1000) // 10 minutes - in milliseconds
  private void scheduledTaskUpdateCollections() {
    List<AidrCollection> collections;
    try {
      collections = collectionService.getRunningCollections();
    } catch (Exception e) {
      logger.error("Error while executing update collections scheduled task", e);
      taggerService.sendMailService(
          "Error in ScheduledTask",
          "Error while executing update collections scheduled task in ScheduledTask.scheduledTaskUpdateCollections");
      return;
    }
    if (collections != null) {
      logger.info(
          "Update collections scheduled task started for " + collections.size() + " collections");

      for (AidrCollection item : collections) {
        try {
          collectionService.statusByCollection(item);
        } catch (Exception e) {
          logger.error("Error while updating collection with ID: " + item.getId(), e);
          taggerService.sendMailService(
              "Error in ScheduledTask",
              "Error while executing  updating collection with ID: "
                  + item.getId()
                  + " in ScheduledTask.scheduledTaskUpdateCollections");
        }
      }
    }
    logger.info("Update collections scheduled task completed.");
  }
示例#11
0
  /**
   * Reads the specified .machines file to get host names
   *
   * @param fileName
   * @throws IOException
   */
  private static void readEmulators(String fileName) throws IOException {
    try {
      FileInputStream is = new FileInputStream(fileName);
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder parser = factory.newDocumentBuilder();

      Document d = parser.parse(is);

      Element e = d.getDocumentElement();

      NodeList n = e.getElementsByTagName("emul");

      // For every class
      String hostName = null;
      for (int i = 0; i < n.getLength(); i++) {
        Element x = (Element) n.item(i);

        hostName = x.getAttribute("hostname");
        emulators.add(hostName);
      }

      is.close();

    } catch (ParserConfigurationException pce) {
      log.error(pce.getMessage());

    } catch (SAXException se) {
      log.error(se.getMessage());
    }
  }
  /** Stores an item if the latter is found waiting in the queue */
  public void run() {
    Item item = null;
    while (isAlive) {
      try {
        item = take();
        if (item == null) {
          _logger.error("Item is null.");
        } else {
          process(item);
        }
      } catch (IOException e) {
        e.printStackTrace();
        _logger.error(e);
      }
    }

    // empty queue
    while ((item = poll()) != null) {
      try {
        process(item);
      } catch (IOException e) {
        e.printStackTrace();
        _logger.error(e);
      }
    }
  }
示例#13
0
 public void run() {
   while (true) {
     try {
       accessToken = WeixinUtil.getAccessToken(appid, appsecret);
       if (null != accessToken) {
         log.info(
             "获取access_token成功,有效时长{}秒 token:{}==="
                 + accessToken.getExpiresIn()
                 + "    "
                 + accessToken.getToken());
         // 休眠7000秒
         Thread.sleep((accessToken.getExpiresIn() - 200) * 1000);
       } else {
         // 如果access_token为null,60秒后再获取
         Thread.sleep(60 * 1000);
       }
     } catch (InterruptedException e) {
       try {
         Thread.sleep(60 * 1000);
       } catch (InterruptedException e1) {
         log.error("{}", e1);
       }
       log.error("{}", e);
     }
   }
 }
  public void collectQueueStats(
      final Azure azure,
      final String namespaceName,
      Set<String> queueNames,
      Set<String> queueStats,
      int queueThreads)
      throws TaskExecutionException {

    final Map<String, String> valueMap = createValueMap(azure, namespaceName, QUEUES, queueStats);

    ListeningExecutorService queueService =
        MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(queueThreads));
    final CountDownLatch countDownLatch = new CountDownLatch(queueNames.size());

    try {
      for (final String queueName : queueNames) {
        try {
          ListenableFuture getQueueNames =
              queueService.submit(
                  new Runnable() {
                    public void run() {
                      getStatsFromAzure(azure, namespaceName, valueMap, queueName, QUEUES);
                    }
                  });

          Futures.addCallback(
              getQueueNames,
              new FutureCallback<Void>() {
                public void onSuccess(Void nothing) {
                  countDownLatch.countDown();
                }

                public void onFailure(Throwable thrown) {
                  countDownLatch.countDown();
                  logger.error(
                      "Unable to get stats for queue ["
                          + queueName
                          + "] in namespace ["
                          + namespaceName
                          + "]",
                      thrown);
                }
              });

        } catch (Exception e) {
          logger.error(
              "Error getting stats for queue [" + namespaceName + "/" + queueName + "]", e);
          throw new TaskExecutionException(
              "Error getting stats for queue [" + namespaceName + "/" + queueName + "]", e);
        }
      }
    } finally {
      queueService.shutdown();
    }
    try {
      countDownLatch.await();
    } catch (InterruptedException e) {
      logger.error("Unable to wait till getting the queue stats", e);
    }
  }
  private InputStream processGetRequest(URL url, String keyStore, String keyStorePassword) {
    SSLSocketFactory sslFactory = getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con = null;
    try {
      con = (HttpsURLConnection) url.openConnection();
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    }
    con.setSSLSocketFactory(sslFactory);
    try {
      con.setRequestMethod(REQUEST_METHOD_GET);
    } catch (ProtocolException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    }

    con.addRequestProperty(X_MS_VERSION_HEADER, X_MS_VERSION);

    InputStream responseStream = null;
    try {
      responseStream = (InputStream) con.getContent();
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    }

    return responseStream;
  }
示例#16
0
  // returns recently changed items, checking for accessibility
  private Item[] getItems(Context context, DSpaceObject dso) throws IOException, SQLException {
    try {
      // new method of doing the browse:
      String idx = ConfigurationManager.getProperty("recent.submissions.sort-option");
      if (idx == null) {
        throw new IOException(
            "There is no configuration supplied for: recent.submissions.sort-option");
      }
      BrowseIndex bix = BrowseIndex.getItemBrowseIndex();
      if (bix == null) {
        throw new IOException("There is no browse index with the name: " + idx);
      }

      BrowserScope scope = new BrowserScope(context);
      scope.setBrowseIndex(bix);
      if (dso != null) {
        scope.setBrowseContainer(dso);
      }

      for (SortOption so : SortOption.getSortOptions()) {
        if (so.getName().equals(idx)) {
          scope.setSortBy(so.getNumber());
        }
      }
      scope.setOrder(SortOption.DESCENDING);
      scope.setResultsPerPage(itemCount);

      // gather & add items to the feed.
      BrowseEngine be = new BrowseEngine(context);
      BrowseInfo bi = be.browseMini(scope);
      Item[] results = bi.getItemResults(context);

      if (includeAll) {
        return results;
      } else {
        // Check to see if we can include this item
        // Group[] authorizedGroups = AuthorizeManager.getAuthorizedGroups(context, results[i],
        // Constants.READ);
        // boolean added = false;
        List<Item> items = new ArrayList<Item>();
        for (Item result : results) {
          checkAccess:
          for (Group group :
              AuthorizeManager.getAuthorizedGroups(context, result, Constants.READ)) {
            if ((group.getID() == Group.ANONYMOUS_ID)) {
              items.add(result);
              break checkAccess;
            }
          }
        }
        return items.toArray(new Item[items.size()]);
      }
    } catch (SortException se) {
      log.error("caught exception: ", se);
      throw new IOException(se.getMessage(), se);
    } catch (BrowseException e) {
      log.error("caught exception: ", e);
      throw new IOException(e.getMessage(), e);
    }
  }
示例#17
0
 /**
  * processRequest processes PhaseIV Web Service calls. It creates a soap message from input string
  * xmlRequest and invokes Phase IV Web Service processRequest method.
  *
  * @param PhaseIV xmlRequest
  * @return PhaseIV xmlResponse
  * @throws Exception
  */
 public String processRequest(String xmlRequest, String clientURL) throws Exception {
   try {
     if (Utils.getInstance().isNullString(xmlRequest)
         || Utils.getInstance().isNullString(clientURL)) {
       logger.debug("Recieved xmlRequest or clientURL as null");
       return null;
     }
     logger.debug("processRequest--> xmlRequest :" + xmlRequest);
     ByteArrayInputStream inStream = new ByteArrayInputStream(xmlRequest.getBytes());
     StreamSource source = new StreamSource(inStream);
     MessageFactory msgFactory = MessageFactory.newInstance();
     SOAPMessage sMsg = msgFactory.createMessage();
     SOAPPart sPart = sMsg.getSOAPPart();
     sPart.setContent(source);
     MimeHeaders mimeHeader = sMsg.getMimeHeaders();
     mimeHeader.setHeader("SOAPAction", "http://ejbs.phaseiv.bsg.adp.com");
     logger.debug("processRequest-->in PhaseIVClient before call");
     SOAPMessage respMsg = executeCall(sMsg, clientURL);
     logger.debug("processRequest-->in PhaseIVClient after call");
     // SOAPFault faultCode =
     // respMsg.getSOAPPart().getEnvelope().getBody().getFault();
     ByteArrayOutputStream outStream = new ByteArrayOutputStream();
     respMsg.writeTo(outStream);
     logger.debug("processRequest xmlResponse:" + outStream.toString());
     return outStream.toString();
   } catch (Exception exp) {
     logger.error("processRequest --> Error while processing request : " + exp.getMessage());
     logger.error("processRequest --> error xmlRequest:" + xmlRequest);
     exp.printStackTrace();
     throw exp;
   }
 }
  private void displayFilteredDialog() {
    try {
      log.debug("displayFilteredDialog: subAction name = " + this.m_subAction.sub_action_name());
      // toolbarAction parentAction = getParentAction();

      JDialog initDebaterecord;
      initDebaterecord = new JDialog();
      initDebaterecord.setTitle("Enter Settings for Document");
      initDebaterecord.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
      // initDebaterecord.setPreferredSize(new Dimension(420, 300));

      InitDebateRecord panel =
          new InitDebateRecord(ooDocument, initDebaterecord, m_parentAction, m_subAction);
      // panel.setDialogMode(SelectorDialogModes.TEXT_INSERTION);
      // panel.setBackground(new Color(255, 255, 153));
      // initDebaterecord.setTitle("Selection Mode");
      initDebaterecord.getContentPane().add(panel);
      initDebaterecord.pack();
      initDebaterecord.setLocationRelativeTo(null);
      initDebaterecord.setVisible(true);
      initDebaterecord.setAlwaysOnTop(true);
    } catch (Exception ex) {
      log.error("displayFilteredDialog : " + ex.getMessage());
      log.error(
          "displayFilteredDialog: stack trace :  \n"
              + org.bungeni.ooo.utils.CommonExceptionUtils.getStackTrace(ex));
    }
  }
示例#19
0
  /**
   * Ingest.
   *
   * @param foxml the foxml
   * @param label the label
   * @param uuid the uuid
   * @param model the model
   * @param topLevelUuid the top level uuid
   * @param inputDirPath the input dir path
   * @return true, if successful
   */
  public static boolean ingest(
      String foxml,
      String label,
      String uuid,
      String model,
      String topLevelUuid,
      String inputDirPath) {

    if (uuid != null && !uuid.startsWith(Constants.FEDORA_UUID_PREFIX)) {
      uuid = Constants.FEDORA_UUID_PREFIX + uuid;
    }

    if (LOGGER.isInfoEnabled()) {
      LOGGER.info(
          "Ingesting the digital object with PID"
              + (!uuid.contains("uuid:") ? " uuid:" : " ")
              + uuid
              + " label:"
              + label
              + ", model: "
              + model);
    }

    String login = config.getFedoraLogin();
    String password = config.getFedoraPassword();
    String url = config.getFedoraHost() + "/objects/new";
    boolean success = RESTHelper.post(url, foxml, login, password, false);

    if (LOGGER.isInfoEnabled() && success) {
      LOGGER.info("Object ingested -- uuid:" + uuid + " label: " + label + ", model: " + model);
    }

    if (topLevelUuid != null && inputDirPath != null && INGEST_LOGGER.isInfoEnabled()) {
      INGEST_LOGGER.info(String.format("%s %16s %s", uuid, model, label));
    }
    if (success) {
      if (topLevelUuid != null && inputDirPath != null) {
        try {
          if (!uuid.equals(topLevelUuid)) {
            // TODO-MR
            //                        digitalObjectDAO.insertNewDigitalObject(uuid,
            //                                                                model,
            //                                                                label,
            //                                                                inputDirPath,
            //                                                                topLevelUuid,
            //                                                                false);
          } else {
            digitalObjectDAO.updateTopObjectTime(uuid);
          }
        } catch (DatabaseException e) {
          LOGGER.error("DB ERROR!!!: " + e.getMessage() + ": " + e);
          e.printStackTrace();
        }
      }
    } else {
      LOGGER.error(
          "Unable to ingest object uuid:" + uuid + " label: " + label + ", model: " + model);
    }
    return success;
  }
示例#20
0
 /**
  * 更新任务
  *
  * @param task
  * @throws SQLException
  */
 public long update(Task task) throws SQLException {
   // ID,NAME,STATUS,CTIME,FTIME,MESSAGE
   String upSql =
       "update " + TABLE_NAME + " set NAME=?,STATUS=?,CTIME=?,FTIME=?,MESSAGE=? where ID=?";
   Connection conn = null;
   PreparedStatement upStmt = null;
   try {
     conn = DBUtil.getConnection();
     conn.setAutoCommit(false);
     upStmt = conn.prepareStatement(upSql);
     upStmt.setString(1, task.getName());
     upStmt.setInt(2, task.getStatus());
     upStmt.setLong(3, task.getcTime());
     upStmt.setLong(4, task.getfTime());
     upStmt.setString(5, task.getMessage());
     upStmt.setLong(6, task.getId());
     upStmt.execute();
     this.orderDAO.update(conn, task.getOrders());
     conn.commit();
     return task.getId();
   } catch (Exception e) {
     LOG.error("Will rollback");
     conn.rollback();
     LOG.error(e.getMessage(), e);
     throw new RuntimeException(e);
   } finally {
     if (upStmt != null) {
       upStmt.close();
     }
     if (conn != null) {
       conn.close();
     }
   }
 }
  public static ResultSet Read() throws ResponseException {
    ResultSet rs = null;
    PreparedStatement statement = null;
    String query = "select * from unlocked;";
    Connection connect = null;
    CachedRowSet crs = null;
    IConnection c = MiscUtil.getIConnection();

    try (CachedRowSet crs2 = RowSetProvider.newFactory().createCachedRowSet()) {
      connect = c.init();
      statement = connect.prepareStatement(query);
      rs = statement.executeQuery();
      crs2.populate(rs);
      crs = crs2.createCopy();
    } catch (SQLException e) {
      logger.error("SQL Error", e);
      throw new ResponseException("SQL Error", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (ResponseException e) {
      throw e;
    } finally {
      try {
        if (statement != null) statement.close();
        if (connect != null) connect.close();
      } catch (SQLException e) {
        logger.error("SQL Error", e);
      }
    }
    return (crs);
  }
示例#22
0
  public synchronized Object fromXML(java.io.Reader input) throws XMLUtilityException {
    Object beanObject;

    org.exolab.castor.xml.Unmarshaller unmarshaller = null;
    try {
      log.debug("Creating unmarshaller");
      unmarshaller = new org.exolab.castor.xml.Unmarshaller(this.getMapping());
    } catch (MappingException e) {
      log.error("XML mapping file is invalid: ", e);
      throw new XMLUtilityException("XML mapping file invalid: ", e);
    } catch (Exception e) {
      log.error("General Exception caught trying to create unmarshaller: ", e);
      throw new XMLUtilityException("General Exception caught trying to create unmarshaller: ", e);
    }

    try {
      log.debug("About to unmarshal from input ");
      beanObject = unmarshaller.unmarshal(input);
    } catch (MarshalException e) {
      log.error("Error marshalling input: ", e);
      throw new XMLUtilityException("Error unmarshalling xml input: " + e.getMessage(), e);
    } catch (ValidationException e) {
      log.error("Error in xml validation when unmarshalling xml input: ", e);
      throw new XMLUtilityException("Error in xml validation when unmarshalling xml input: ", e);
    }
    return beanObject;
  }
  /** Finishes the execution context */
  public static void finish() {
    Connection conn = JForumExecutionContext.getConnection(false);

    if (conn != null) {
      if (SystemGlobals.getBoolValue(ConfigKeys.DATABASE_USE_TRANSACTIONS)) {
        if (JForumExecutionContext.shouldRollback()) {
          try {
            conn.rollback();
          } catch (Exception e) {
            logger.error("Error while rolling back a transaction", e);
          }
        } else {
          try {
            conn.commit();
          } catch (Exception e) {
            logger.error("Error while commiting a transaction", e);
          }
        }
      }

      try {
        DBConnection.getImplementation().releaseConnection(conn);
      } catch (Exception e) {
        logger.error("Error while releasing the connection : " + e, e);
      }
    }

    userData.set(null);
  }
示例#24
0
  /**
   * 购买商品-生成订单
   *
   * @author zhliu
   * @date 2015年6月19日
   * @parm
   * @param request
   * @param response
   * @param packageId : 套餐ID
   * @param count
   * @return
   */
  @RequestMapping("/buyProdOrder")
  public String buyProdOrder(HttpServletRequest request, RequestBookingOrder bookingOrder) {

    Order order = new Order();

    try {
      User user = (User) request.getSession().getAttribute(SecurityConstants.SESSION_USER);

      bookingOrder.setUserId(user.getObjectId());
      bookingOrder.setOrderType(IBSConstants.ORDER_TYPE_POINT_BUY); // 年度福利
      bookingOrder.setOrderSource(IBSConstants.ORDER_SOURCE_HR); // 企业HR端
      bookingOrder.setOrderProductType(
          IBSConstants.ORDER_PRODUCT_TYPE_WELFARE); // 订单商品类型  1福利套餐,2体检套餐,3SKU商品,4生活服务
      bookingOrder.setUserId(user.getObjectId());

      logger.info("HR端购买福利 --购买商品---开始");
      order = orderManager.createImmediateOrder(bookingOrder);
      logger.info("HR端购买福利 --购买商品---结束");
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("HR端购买福利 --购买商品---失败");
      logger.error(e.getMessage());
    }

    return "redirect:" + "buyWelfareOrderSuc/" + order.getObjectId();
  }
示例#25
0
  public void parseFile(File file) {
    log.debug("Will attempt to process the file: " + file.getAbsolutePath());
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new FileReader(file));
    } catch (FileNotFoundException e) {
      log.error("Unable to read the input file. Error: " + e);
      throw new RuntimeException("Unable to read the input file.");
    }

    try {
      boolean done = false;
      int lineIndex = 0;
      while (!done) {
        String line = reader.readLine();
        if (line == null) {
          done = true;
          continue;
        }
        processLine(line, lineIndex++);
      }
    } catch (IOException e) {
      log.error("Failed while loading the input file. Error: " + e);
      throw new RuntimeException("Failed while loading the input file.");
    }
  }
  public static void backSearchKeyWord() {
    Session sessionBase = HibernateCountUtil.currentSession();
    Connection countCon = getCountJDBCCon();
    try {
      countCon.setAutoCommit(false);
      long b = new Date().getTime();
      backAllByPage(sessionBase, countCon);
      // 备份每个月的数据
      countCon.commit();
      logger.info("备份事务提交");
      logger.info("关键字日志备份初始化完成,耗时【" + (new Date().getTime() - b) + "】毫秒");

    } catch (SQLException e) {
      try {
        countCon.rollback();
      } catch (SQLException e1) {
        logger.error(e1.getMessage(), e1);
      }
      logger.error(e.getMessage(), e);
    } finally {
      try {
        countCon.close();
      } catch (SQLException e) {
        logger.error(e.getMessage(), e);
      }
    }
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String oldPassword = req.getParameter(HttpConstants.HTTP_VAR_OLD_PASSWORD);
    String newPassword = req.getParameter(HttpConstants.HTTP_VAR_NEW_PASSWORD);
    String confirmNewPassword = req.getParameter(HttpConstants.HTTP_VAR_CONFIRM_NEW_PASSWORD);

    if ((oldPassword == null) || (newPassword == null) || (confirmNewPassword == null)) {
    } else {
      try {
        PasswordManager.changePassword(
            Connector.getInstance().getConnection(),
            UserSession.Factory.getUserSession(req).getUser(),
            oldPassword,
            newPassword,
            confirmNewPassword);
        req.setAttribute(HttpConstants.ATTR_VAR_CHANGE_PASSWORD_SUCCESS, true);
      } catch (DaoException ex) {
        logger.error(ex);
      } catch (NamingException ex) {
        logger.error(ex);
      } catch (SQLException ex) {
        logger.error(ex);
      } catch (InvalidPasswordException ex) {
        req.setAttribute(HttpConstants.ATTR_VAR_CHANGE_PASSWORD_ERROR, ex.getMessage());
      } catch (Exception e) {
        logger.error(e);
      }
    }

    req.getRequestDispatcher("/pages/change-password.jsp").forward(req, resp);

    return;
  }
示例#28
0
  void createClient() throws Exception {
    PathBasedZkSerializer zkSerializer =
        ChainedPathZkSerializer.builder(new ZNRecordStreamingSerializer()).build();

    _zkclient =
        new ZkClient(
            _zkAddress, _sessionTimeout, ZkClient.DEFAULT_CONNECTION_TIMEOUT, zkSerializer);

    _baseDataAccessor = createBaseDataAccessor();

    _dataAccessor = new ZKHelixDataAccessor(_clusterName, _instanceType, _baseDataAccessor);
    _configAccessor = new ConfigAccessor(_zkclient);

    int retryCount = 0;

    _zkclient.subscribeStateChanges(this);
    while (retryCount < 3) {
      try {
        _zkclient.waitUntilConnected(_sessionTimeout, TimeUnit.MILLISECONDS);
        handleStateChanged(KeeperState.SyncConnected);
        handleNewSession();
        break;
      } catch (HelixException e) {
        LOG.error("fail to createClient.", e);
        throw e;
      } catch (Exception e) {
        retryCount++;

        LOG.error("fail to createClient. retry " + retryCount, e);
        if (retryCount == 3) {
          throw e;
        }
      }
    }
  }
示例#29
0
 public static void register(GaiaDAOAgent agent) {
   if (daoAgentList == null) {
     try {
       daoAgentList = new ArrayList();
       daoCallerAgent = new DAOCallerAgent();
       String containerName = agent.getContainerController().getContainerName();
       Integer id = new Integer(containerName.substring(6));
       AgentController controller =
           agent
               .getContainerController()
               .acceptNewAgent(
                   DAOCallerAgent.class.getSimpleName() + "-" + id + "-0", daoCallerAgent);
       controller.start();
       positionCallerAgent = new DAOCallerAgent();
       logger.error("accept agent PositionCallerAgent-" + id + "-0 from " + agent.getName());
       controller =
           agent
               .getContainerController()
               .acceptNewAgent("PositionCallerAgent-" + id + "-0", positionCallerAgent);
       controller.start();
     } catch (ControllerException | NumberFormatException e) {
       logger.error(StringUtils.formatErrorMessage(e));
     }
   }
   daoAgentList.add(agent);
 }
示例#30
0
 /**
  * Return a new instance of task result represented by a task id and its exception.
  *
  * @param id the identification of the task that send this result.
  * @param exception the exception that occurred in the task.
  * @param output the output of the task.
  * @param execDuration the execution duration of the task itself
  * @param propagatedProperties the map of all properties that has been propagated through
  *     Exporter.propagateProperty
  */
 public TaskResultImpl(
     TaskId id,
     Throwable exception,
     TaskLogs output,
     long execDuration,
     Map<String, BigString> propagatedProperties) {
   this(id, output);
   this.taskDuration = execDuration;
   this.exception = exception;
   this.propagatedProperties = propagatedProperties;
   try {
     // try to serialize the user exception
     this.serializedException = ObjectToByteConverter.ObjectStream.convert(exception);
   } catch (IOException ioe2) {
     // cannot serialize the exception
     logger.error("", ioe2);
     try {
       // serialize a NotSerializableException with the cause message
       this.serializedException =
           ObjectToByteConverter.ObjectStream.convert(
               new NotSerializableException(ioe2.getMessage()));
     } catch (IOException ioe3) {
       // this should not append as the NotSerializableException is serializable and
       // the given argument is a string (also serializable)
       logger.error("", ioe3);
     }
   }
 }