Ejemplo n.º 1
0
  /**
   * @param springCfgPath Spring configuration file path.
   * @return Grid configuration.
   * @throws Exception If failed.
   */
  protected static IgniteConfiguration loadConfiguration(String springCfgPath) throws Exception {
    URL url;

    try {
      url = new URL(springCfgPath);
    } catch (MalformedURLException e) {
      url = IgniteUtils.resolveIgniteUrl(springCfgPath);

      if (url == null)
        throw new IgniteCheckedException(
            "Spring XML configuration path is invalid: "
                + springCfgPath
                + ". Note that this path should be either absolute or a relative local file system path, "
                + "relative to META-INF in classpath or valid URL to IGNITE_HOME.",
            e);
    }

    GenericApplicationContext springCtx;

    try {
      springCtx = new GenericApplicationContext();

      new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(url));

      springCtx.refresh();
    } catch (BeansException e) {
      throw new Exception(
          "Failed to instantiate Spring XML application context [springUrl="
              + url
              + ", err="
              + e.getMessage()
              + ']',
          e);
    }

    Map<String, IgniteConfiguration> cfgMap;

    try {
      cfgMap = springCtx.getBeansOfType(IgniteConfiguration.class);
    } catch (BeansException e) {
      throw new Exception(
          "Failed to instantiate bean [type="
              + IgniteConfiguration.class
              + ", err="
              + e.getMessage()
              + ']',
          e);
    }

    if (cfgMap == null || cfgMap.isEmpty())
      throw new Exception("Failed to find ignite configuration in: " + url);

    return cfgMap.values().iterator().next();
  }
Ejemplo n.º 2
0
  /**
   * Standard way of initializing this filter. Map config parameters onto bean properties of this
   * filter, and invoke subclass initialization.
   *
   * @param filterConfig the configuration for this filter
   * @throws ServletException if bean properties are invalid (or required properties are missing),
   *     or if subclass initialization fails.
   * @see #initFilterBean
   */
  public final void init(FilterConfig filterConfig) throws ServletException {
    Assert.notNull(filterConfig, "FilterConfig must not be null");
    if (logger.isDebugEnabled()) {
      logger.debug("Initializing filter '" + filterConfig.getFilterName() + "'");
    }

    this.filterConfig = filterConfig;

    // Set bean properties from init parameters.
    try {
      PropertyValues pvs = new FilterConfigPropertyValues(filterConfig, this.requiredProperties);
      BeanWrapper bw = new BeanWrapperImpl(this);
      ResourceLoader resourceLoader =
          new ServletContextResourceLoader(filterConfig.getServletContext());
      bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader));
      initBeanWrapper(bw);
      bw.setPropertyValues(pvs, true);
    } catch (BeansException ex) {
      String msg =
          "Failed to set bean properties on filter '"
              + filterConfig.getFilterName()
              + "': "
              + ex.getMessage();
      logger.error(msg, ex);
      throw new NestedServletException(msg, ex);
    }

    // Let subclasses do whatever initialization they like.
    initFilterBean();

    if (logger.isDebugEnabled()) {
      logger.debug("Filter '" + filterConfig.getFilterName() + "' configured successfully");
    }
  }
Ejemplo n.º 3
0
 @RequestMapping(value = "list", method = RequestMethod.GET)
 public String list(ModelMap model) {
   try {
     model.addAttribute(REFRESHS, new ArrayList<String>(allRefresh().keySet()));
     return "manage/refresh";
   } catch (BeansException e) {
     throw new SystemException(e.getMessage(), e);
   }
 }
 @Test
 public void testInt2718FailForGatewayRequestChannelAttribute() {
   try {
     new ClassPathXmlApplicationContext(
             "HttpOutboundGatewayWithinChainTests-fail-context.xml", this.getClass())
         .close();
     fail("Expected BeanDefinitionParsingException");
   } catch (BeansException e) {
     assertTrue(e instanceof BeanDefinitionParsingException);
     assertTrue(e.getMessage().contains("'request-channel' attribute isn't allowed for a nested"));
   }
 }
Ejemplo n.º 5
0
  /**
   * Do pagina primera.
   *
   * @param mapping the mapping
   * @param actionForm the action form
   * @param request the request
   * @param response the response
   * @return the action forward
   * @throws Exception the exception
   */
  public final ActionForward doPaginaPrimera(
      final ActionMapping mapping,
      final ActionForm actionForm,
      final HttpServletRequest request,
      final HttpServletResponse response)
      throws Exception {

    PseudoResponse res = new PseudoResponse(request, response);
    ReporteConciliacionForm form;
    String error = "";
    int pagActual = Integer.parseInt(request.getParameter(PAG_ACTUAL));
    final Boolean repBoletas =
        (request.getParameter(REP_BOLETAS) == null)
            ? false
            : Boolean.parseBoolean(request.getParameter(REP_BOLETAS));
    if (actionForm instanceof ReporteConciliacionForm) {
      form = (ReporteConciliacionForm) actionForm;
    } else {
      form = new ReporteConciliacionForm();
    }

    try {
      final ReporteConciliacionService service =
          (ReporteConciliacionService)
              getWebApplicationContext().getBean(REPORTE_CONCILIACION_SERVICE);

      if (form.getPaginacion() == null) {
        form = new ReporteConciliacionForm();
        error = ConciliaErrorKeys.PPINV_ERR_CONCILIACION_CONSULTA_REPORTE.toString();
        res.setResponseContent(jsonize(form));
      }

      if ("".equals(error)) {
        form = service.consultaOperConciliacion(form, "paginaPrimera", pagActual, repBoletas);
        res.setResponseError(null);
        res.setResponseContent(jsonize(form));
      } else {
        res.setResponseError(error);
      }
    } catch (FrontClientException e) {
      LOG.error(e.getMessage(), e);
      res.setResponseError(e.getMessage());
    } catch (BeansException e) {
      LOG.error(e.getMessage(), e);
      res.setResponseError(GralErrorKeys.PPINV_ERR_GRAL.toString());
    } finally {
      res.commit();
    }

    return null;
  }
  /**
   * Gets Spring application context by given path.
   *
   * @param path Spring application context configuration path.
   * @return Spring application context.
   * @throws IgniteCheckedException If given path or xml-configuration at this path is invalid.
   */
  private GenericApplicationContext getSpringContext(String path) throws IgniteCheckedException {
    try {
      GenericApplicationContext ctx = new GenericApplicationContext();

      new XmlBeanDefinitionReader(ctx)
          .loadBeanDefinitions(new UrlResource(U.resolveIgniteUrl(path)));

      ctx.refresh();

      return ctx;
    } catch (BeansException e) {
      throw new IgniteCheckedException(
          "Failed to instantiate Spring XML application context: " + e.getMessage(), e);
    }
  }
  /**
   * doUpdate
   *
   * @param nodeId a int.
   * @param retry a boolean.
   * @throws org.opennms.netmgt.provision.ProvisioningAdapterException if any.
   */
  @Override
  public void doUpdateNode(final int nodeId) throws ProvisioningAdapterException {
    log().debug("doUpdate: updating nodeid: " + nodeId);

    final OnmsNode node = m_nodeDao.get(nodeId);
    Assert.notNull(node, "doUpdate: failed to return node for given nodeId:" + nodeId);

    final InetAddress ipaddress =
        m_template.execute(
            new TransactionCallback<InetAddress>() {
              public InetAddress doInTransaction(final TransactionStatus arg0) {
                return getIpForNode(node);
              }
            });

    final SnmpAgentConfig agentConfig = m_snmpConfigDao.getAgentConfig(ipaddress);

    final OnmsAssetRecord asset = node.getAssetRecord();
    m_config.getReadLock().lock();
    try {
      for (AssetField field : m_config.getAssetFieldsForAddress(ipaddress, node.getSysObjectId())) {
        try {
          String value =
              fetchSnmpAssetString(agentConfig, field.getMibObjs(), field.getFormatString());
          if (log().isDebugEnabled()) {
            log()
                .debug(
                    "doUpdate: Setting asset field \"" + field.getName() + "\" to value: " + value);
          }
          // Use Spring bean-accessor classes to set the field value
          BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(asset);
          try {
            wrapper.setPropertyValue(field.getName(), value);
          } catch (BeansException e) {
            log()
                .warn(
                    "doUpdate: Could not set property \""
                        + field.getName()
                        + "\" on asset object: "
                        + e.getMessage(),
                    e);
          }
        } catch (MissingFormatArgumentException e) {
          // This exception is thrown if the SNMP operation fails or an incorrect number of
          // parameters is returned by the agent or because of a misconfiguration.
          log()
              .warn(
                  "doUpdate: Could not set value for asset field \""
                      + field.getName()
                      + "\": "
                      + e.getMessage(),
                  e);
        }
      }
    } finally {
      m_config.getReadLock().unlock();
    }
    node.setAssetRecord(asset);
    m_nodeDao.saveOrUpdate(node);
    m_nodeDao.flush();
  }
Ejemplo n.º 8
0
  /*
   * (non-Javadoc)
   *
   * @see org.jpos.q2.QBeanSupport#startService()
   */
  public void startService() {
    ApplicationContext dependencyCtx = null;

    if ((null != springCtxDepRegistrationKey)
        && (springCtxDepRegistrationKey.trim().length() > 0)) {
      try {
        log.debug(
            String.format(
                "Spring Q2MBean '%s' : search for Spring context dependency '%s' in NameRegistrar",
                getName(), springCtxDepRegistrationKey));

        Object object = NameRegistrar.get(springCtxDepRegistrationKey);
        if (object instanceof Spring) {
          dependencyCtx = ((Spring) object).getContext();
        } else if (object instanceof ApplicationContext) {
          dependencyCtx = ((ApplicationContext) object);
        } else {
          String errMsg =
              String.format(
                  "Spring Q2MBean '%s' : spring context dependency '%s' found in NameRegistrar but is not a Spring ApplicaitonContext, neither a Spring QBean",
                  getName(), springCtxDepRegistrationKey);
          log.error(errMsg);
          throw new RuntimeException(errMsg);
        }

        log.debug(
            String.format(
                "Spring Q2MBean '%s' : Spring context dependency '%s' found in NameRegistrar",
                getName(), springCtxDepRegistrationKey));
      } catch (NotFoundException e) {
        if (!this.springCtxDepOptional) {
          log.error(
              String.format(
                  "Spring Q2MBean '%s' : spring context dependency '%s' not found in NameRegistrar",
                  getName(), springCtxDepRegistrationKey));
          throw new RuntimeException(e);
        } else {
          log.info(
              String.format(
                  "Spring Q2MBean '%s' : optional spring context dependency '%s' not found in NameRegistrar",
                  getName(), springCtxDepRegistrationKey));
        }
      }
    }

    try {
      if (null == dependencyCtx) {
        context = new FileSystemXmlApplicationContext(configFiles);
      } else {
        context = new FileSystemXmlApplicationContext(configFiles, dependencyCtx);
      }
      log.info(String.format("Spring Q2MBean '%s' : spring context has been loaded", getName()));
    } catch (BeansException e) {
      log.error(
          String.format(
              "Spring Q2MBean '%s' : an error occured while loading this spring context. Error message = %s",
              getName(), e.getMessage()));
      throw e;
    }

    NameRegistrar.register(getName(), this);
  }
Ejemplo n.º 9
0
  /**
   * See <a href="http://e-docs.bea.com/wls/docs100/javadocs/weblogic/common/T3StartupDef.html">
   * http://e-docs.bea.com/wls/docs100/javadocs/weblogic/common/T3StartupDef.html</a> for more
   * information.
   *
   * @param str Virtual name by which the class is registered as a {@code startupClass} in the
   *     {@code config.xml} file
   * @param params A hashtable that is made up of the name-value pairs supplied from the {@code
   *     startupArgs} property
   * @return Result string (log message).
   * @throws Exception Thrown if error occurred.
   */
  @SuppressWarnings({"unchecked", "CatchGenericClass"})
  @Override
  public String startup(String str, Hashtable params) throws Exception {
    GridLogger log = new GridJavaLogger(LoggingHelper.getServerLogger());

    cfgFile = (String) params.get(cfgFilePathParam);

    if (cfgFile == null) {
      throw new IllegalArgumentException("Failed to read property: " + cfgFilePathParam);
    }

    String workMgrName = (String) params.get(workMgrParam);

    URL cfgUrl = U.resolveGridGainUrl(cfgFile);

    if (cfgUrl == null)
      throw new ServerLifecycleException(
          "Failed to find Spring configuration file (path provided should be "
              + "either absolute, relative to GRIDGAIN_HOME, or relative to META-INF folder): "
              + cfgFile);

    GenericApplicationContext springCtx;

    try {
      springCtx = new GenericApplicationContext();

      XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(springCtx);

      xmlReader.loadBeanDefinitions(new UrlResource(cfgUrl));

      springCtx.refresh();
    } catch (BeansException e) {
      throw new ServerLifecycleException(
          "Failed to instantiate Spring XML application context: " + e.getMessage(), e);
    }

    Map cfgMap;

    try {
      // Note: Spring is not generics-friendly.
      cfgMap = springCtx.getBeansOfType(GridConfiguration.class);
    } catch (BeansException e) {
      throw new ServerLifecycleException(
          "Failed to instantiate bean [type="
              + GridConfiguration.class
              + ", err="
              + e.getMessage()
              + ']',
          e);
    }

    if (cfgMap == null)
      throw new ServerLifecycleException(
          "Failed to find a single grid factory configuration in: " + cfgUrl);

    if (cfgMap.isEmpty())
      throw new ServerLifecycleException("Can't find grid factory configuration in: " + cfgUrl);

    try {
      ExecutorService execSvc = null;

      MBeanServer mbeanSrv = null;

      for (GridConfiguration cfg : (Collection<GridConfiguration>) cfgMap.values()) {
        assert cfg != null;

        GridConfigurationAdapter adapter = new GridConfigurationAdapter(cfg);

        // Set logger.
        if (cfg.getGridLogger() == null) adapter.setGridLogger(log);

        if (cfg.getExecutorService() == null) {
          if (execSvc == null)
            execSvc =
                workMgrName != null
                    ? new GridThreadWorkManagerExecutor(workMgrName)
                    : new GridThreadWorkManagerExecutor(J2EEWorkManager.getDefault());

          adapter.setExecutorService(execSvc);
        }

        if (cfg.getMBeanServer() == null) {
          if (mbeanSrv == null) {
            InitialContext ctx = null;

            try {
              ctx = new InitialContext();

              mbeanSrv = (MBeanServer) ctx.lookup("java:comp/jmx/runtime");
            } catch (Exception e) {
              throw new IllegalArgumentException(
                  "MBean server was not provided and failed to obtain " + "Weblogic MBean server.",
                  e);
            } finally {
              if (ctx != null) ctx.close();
            }
          }

          adapter.setMBeanServer(mbeanSrv);
        }

        Grid grid = G.start(adapter, springCtx);

        // Test if grid is not null - started properly.
        if (grid != null) gridNames.add(grid.name());
      }

      return getClass().getSimpleName() + " started successfully.";
    } catch (GridException e) {
      // Stop started grids only.
      for (String name : gridNames) G.stop(name, true);

      throw new ServerLifecycleException("Failed to start GridGain.", e);
    }
  }