/**
   * Initialize this plugin. This method only called when the plugin is instantiated.
   *
   * @throws PluginException If there is an error initializing the plugin
   */
  public void init() throws PluginException {
    super.init();

    _mailServer = _servletConfig.getInitParameter(EmailConstants.SMTPSERVER_IP);

    if (_mailServer != null) {
      if (_mailServer.startsWith("java:comp/env")) {
        try {
          Context context = new InitialContext();
          _session = (Session) context.lookup(_mailServer);
        } catch (NamingException e) {
          if (_logger.isErrorEnabled()) {
            _logger.error(e);
          }

          throw new PluginException(e);
        }
      } else {
        _mailServerUsername =
            _servletConfig.getInitParameter(EmailConstants.SMTPSERVER_USERNAME_IP);
        _mailServerPassword =
            _servletConfig.getInitParameter(EmailConstants.SMTPSERVER_PASSWORD_IP);
      }
    } else {
      if (_logger.isErrorEnabled()) {
        _logger.error(
            "Missing SMTP servername servlet initialization parameter: "
                + EmailConstants.SMTPSERVER_IP);
      }
    }

    _ipAddressCommentTimes = new WeakHashMap();
    _eventBroadcaster.addListener(this);
  }
예제 #2
0
  protected void validateRequiredSystemProperties() {
    String jndiPropertiesDir = System.getProperty(CartridgeAgentConstants.JNDI_PROPERTIES_DIR);

    if (StringUtils.isBlank(jndiPropertiesDir)) {
      if (log.isErrorEnabled()) {
        log.error(
            String.format(
                "System property not found: %s", CartridgeAgentConstants.JNDI_PROPERTIES_DIR));
      }
      return;
    }

    String payloadPath = System.getProperty(CartridgeAgentConstants.PARAM_FILE_PATH);
    if (StringUtils.isBlank(payloadPath)) {
      if (log.isErrorEnabled()) {
        log.error(
            String.format(
                "System property not found: %s", CartridgeAgentConstants.PARAM_FILE_PATH));
      }
      return;
    }

    String extensionsDir = System.getProperty(CartridgeAgentConstants.EXTENSIONS_DIR);
    if (StringUtils.isBlank(extensionsDir)) {
      if (log.isWarnEnabled()) {
        log.warn(
            String.format("System property not found: %s", CartridgeAgentConstants.EXTENSIONS_DIR));
      }
    }
  }
  protected void mergeFileTemplate(Template pTemplate, Context pContext, Writer pWriter)
      throws MergeTemplateException {

    Properties props = WebMacroHelper.getDefaultProperties();
    props.putAll(this.properties);

    props.setProperty("TemplateEncoding", pTemplate.getInputEncoding());
    String path = pTemplate.getResource();
    if (log.isDebugEnabled()) {
      log.debug("模板文件: \"" + path + "\" 采用WebMacro引擎进行合并.");
      log.debug("模板文件: \"" + path + "\" 输入编码方式是:" + pTemplate.getInputEncoding());
    }

    /**
     * @FIXME 由于WebMacro没有提供运行时,设置模板编码方式,所以要求每次实例化Engine,这样性能有些影响,希望以后版本
     * WebMacro会提供该方法。不过好在,是单机版本的,性能问题不大.
     */
    WM wm = WebMacroHelper.getWMEngine(props);

    org.webmacro.Context c = new org.webmacro.Context(wm.getBroker());
    Map params = pContext.getParameters();
    for (Iterator i = params.keySet().iterator(); i.hasNext(); ) {
      String key = (String) i.next();
      Object value = params.get(key);
      c.put(key, value);
    }

    org.webmacro.Template t = null;
    try {
      t = wm.getTemplate(pTemplate.getResource());
    } catch (ResourceException e) {
      final String MSG = "合并模板文件 \"" + path + "\"  失败!" + e.getMessage();
      if (log.isErrorEnabled()) {
        log.error(MSG, e);
      }
      throw new MergeTemplateException(MSG, e);
    }

    String result = null;
    try {
      //			result = t.evaluateAsString(c);
      //		} catch (PropertyException e) {
    } catch (Exception e) {
      final String MSG = "合并模板文件 \"" + path + "\"  失败!" + e.getMessage();
      if (log.isErrorEnabled()) {
        log.error(MSG, e);
      }
      throw new MergeTemplateException(MSG, e);
    }

    try {
      pWriter.write(result);
    } catch (IOException e) {
      final String MSG = "合并模板文件 \"" + path + "\"  失败!" + e.getMessage();
      if (log.isErrorEnabled()) {
        log.error(MSG, e);
      }
      throw new MergeTemplateException(MSG, e);
    }
  }
  @Override
  public <T> T executeWithoutTransaction(final OperationCallback<T> action)
      throws OperationException, Exception {

    DataSourceType dataSourceType = loadBalancerManager.getAliveDataSource();
    if (dataSourceType == null) {
      if (logger.isErrorEnabled()) {
        logger.equals("executeWithoutTransaction -> None of the available datasource");
      }
      throw new OperationException("None of the available datasource");
    }

    OperationCallbackExtend<T> noodleServiceCallbackExtendTemp = null;
    if (action instanceof OperationCallbackExtend) {
      noodleServiceCallbackExtendTemp = (OperationCallbackExtend<T>) action;
    }
    final OperationCallbackExtend<T> noodleServiceCallbackExtend = noodleServiceCallbackExtendTemp;

    T result = null;

    ServiceResult serviceResult = new ServiceResult();

    try {
      DataSourceSwitch.setDataSourceType(dataSourceType);

      if (noodleServiceCallbackExtend != null) {
        if (!noodleServiceCallbackExtend.beforeExecuteActionCheck()) {
          if (logger.isErrorEnabled()) {
            logger.equals("executeWithoutTransaction -> Before execute action check fail");
          }
          throw new OperationException("Before execute action check fail");
        }
        noodleServiceCallbackExtend.beforeExecuteAction();
      }

      try {
        result = action.executeAction();
      } catch (Exception e) {
        if (logger.isErrorEnabled()) {
          logger.equals("executeWithoutTransaction -> Execute action exception, Exception: " + e);
        }
        serviceResult.setSuccess(false);
        serviceResult.setFailException(e);
      }

      if (noodleServiceCallbackExtend != null) {
        noodleServiceCallbackExtend.afterExecuteAction(
            serviceResult.isSuccess(), result, serviceResult.getFailException());
      }

      if (!serviceResult.isSuccess()) {
        throw serviceResult.getFailException();
      }
    } finally {
      DataSourceSwitch.clearDataSourceType();
    }

    return result;
  }
  public void createTrack() {
    java.sql.Connection conn = null;
    try {
      conn = WinConnectionUtil.getAccessDBConnection(config.getString("access.src", ""));

      Statement stmt1 =
          conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      Statement stmt2 = myConn.createStatement();

      String cmd1 =
          "SELECT [tDiscTrack.TrackID], [tDiscTrack.TrackNo], [tDiscTrack.TrackNoIndex], [tDiscTrack.DiscID], [tTrack.DurationAcronym] "
              + "FROM tDiscTrack INNER JOIN tTrack ON tDiscTrack.TrackID = tTrack.TrackID;";
      if (log.isDebugEnabled()) log.debug("accessSQL1:" + cmd1);

      ResultSet rs1 = stmt1.executeQuery(cmd1);
      rs1.last();
      int rowCount1 = rs1.getRow();
      if (rowCount1 == 0) {
        if (log.isWarnEnabled()) log.warn("Get no access info.");
        return;
      }

      rs1.beforeFirst();
      while (rs1.next()) {
        int id = rs1.getInt("TrackID");
        String cmd2 =
            String.format(
                "INSERT INTO TrackMap (TrackID, TrackNo, TrackNoIndex, TrackDesc, DiscID, CDID, ItemID, ItemFlow, ItemIdx, Note) VALUES (%1$d,%2$d,%3$d,'%4$s',%5$d,'',0,0,0,'');",
                id,
                rs1.getInt("TrackNo"),
                rs1.getInt("TrackNoIndex"),
                rs1.getString("DurationAcronym"),
                rs1.getInt("DiscID"));
        // System.out.println(cmd2);

        if (stmt2.executeUpdate(cmd2) == 0) {
          if (log.isWarnEnabled()) log.warn("[DataExist] TrackID:" + id);
        } else {
          if (log.isInfoEnabled()) log.info("[DataInsert] TrackID:" + id);
        }
      }
      rs1.close();
      stmt1.close();
      stmt2.close();

    } catch (SQLException s) {
      if (log.isErrorEnabled()) log.error(s);
    } catch (Exception e) {
      if (log.isErrorEnabled()) log.error(e);
    } finally {

      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException ignore) {
        }
      }
    }
  }
예제 #6
0
  /**
   * Runs the KAAJEE startup controller.
   *
   * @throws ServletException
   */
  public void init() throws ServletException {

    InputStream configFileStream = null;

    // retrieve KAAJEE configuration settings
    String configFileLocation = getInitParameter(CONFIG_FILE_PARAM_NAME);
    if (log.isDebugEnabled()) {
      log.debug("Config File Location: " + configFileLocation);
    }

    // if init-file is not set, then no point in trying
    if (configFileLocation == null) {
      if (log.isErrorEnabled()) {
        StringBuffer sb = new StringBuffer("KAAJEE configuration file location '");
        sb.append(configFileLocation);
        sb.append("' is null; can't retrieve KAAJEE settings.");
        log.error(sb.toString());
      }
    } else {

      if (log.isDebugEnabled()) {
        StringBuffer sb = new StringBuffer("about to try to retrieve '");
        sb.append(configFileLocation);
        sb.append("'");
        log.debug(sb.toString());
      }
      try {
        // read in the XML doc
        configFileStream = getServletContext().getResourceAsStream(configFileLocation);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document configDocument = builder.parse(configFileStream);

        // pass to the startup controller
        StartupController.doStartup(configDocument);

      } catch (FactoryConfigurationError e) {
        log.error("Problem reading configuration file.", e);
      } catch (ParserConfigurationException e) {
        log.error("Problem reading configuration file.", e);
      } catch (SAXException e) {
        log.error("Problem reading configuration file.", e);
      } catch (IOException e) {
        log.error("Problem reading configuration file.", e);
      } finally {

        // close the stream
        try {
          configFileStream.close();
        } catch (IOException e) {
          if (log.isErrorEnabled()) {
            log.error("Problem closing input stream for KAAJEE configuration file.", e);
          }
        }
      }
    }
  }
예제 #7
0
  /** Sends a GET_MBR_REQ to *all* GossipRouters, merges responses. */
  private List _getMembers(String group) {
    List ret = new LinkedList();
    Socket sock = null;
    SocketAddress destAddr;
    DataOutputStream out = null;
    DataInputStream in = null;
    IpAddress entry;
    GossipData gossip_req, gossip_rsp;
    Address mbr;

    for (int i = 0; i < gossip_servers.size(); i++) {
      entry = (IpAddress) gossip_servers.elementAt(i);
      if (entry.getIpAddress() == null || entry.getPort() == 0) {
        if (log.isErrorEnabled()) log.error("entry.host or entry.port is null");
        continue;
      }

      try {
        // sock=new Socket(entry.getIpAddress(), entry.getPort());
        sock = new Socket();
        destAddr = new InetSocketAddress(entry.getIpAddress(), entry.getPort());
        sock.connect(destAddr, SOCKET_TIMEOUT);
        out = new DataOutputStream(sock.getOutputStream());

        gossip_req = new GossipData(GossipRouter.GOSSIP_GET, group, null, null);
        // must send GossipData as fast as possible, otherwise the
        // request might be rejected
        gossip_req.writeTo(out);
        out.flush();

        in = new DataInputStream(sock.getInputStream());
        gossip_rsp = new GossipData();
        gossip_rsp.readFrom(in);
        if (gossip_rsp.mbrs != null) { // merge with ret
          for (Iterator it = gossip_rsp.mbrs.iterator(); it.hasNext(); ) {
            mbr = (Address) it.next();
            if (!ret.contains(mbr)) ret.add(mbr);
          }
        }
      } catch (Exception ex) {
        if (log.isErrorEnabled()) log.error("exception connecting to host " + entry);
      } finally {
        Util.close(out);
        Util.close(in);
        if (sock != null) {
          try {
            sock.close();
          } catch (IOException e) {
          }
        }
      }
    }

    return ret;
  }
  /**
   * Handle an event broadcast from another component
   *
   * @param event {@link org.blojsom.event.Event} to be handled
   */
  public void handleEvent(Event event) {
    if (event instanceof CommentAddedEvent) {
      HtmlEmail email = new HtmlEmail();
      CommentAddedEvent commentAddedEvent = (CommentAddedEvent) event;

      if (commentAddedEvent.getBlog().getBlogEmailEnabled().booleanValue() && _mailServer != null) {
        try {
          setupEmail(commentAddedEvent.getBlog(), commentAddedEvent.getEntry(), email);

          Map emailTemplateContext = new HashMap();
          emailTemplateContext.put(BlojsomConstants.BLOJSOM_BLOG, commentAddedEvent.getBlog());
          emailTemplateContext.put(
              BLOJSOM_COMMENT_PLUGIN_BLOG_COMMENT, commentAddedEvent.getComment());
          emailTemplateContext.put(BLOJSOM_COMMENT_PLUGIN_BLOG_ENTRY, commentAddedEvent.getEntry());

          String htmlText =
              mergeTemplate(
                  COMMENT_PLUGIN_EMAIL_TEMPLATE_HTML,
                  commentAddedEvent.getBlog(),
                  emailTemplateContext);
          String plainText =
              mergeTemplate(
                  COMMENT_PLUGIN_EMAIL_TEMPLATE_TEXT,
                  commentAddedEvent.getBlog(),
                  emailTemplateContext);

          email.setHtmlMsg(htmlText);
          email.setTextMsg(plainText);

          String emailPrefix =
              (String) commentAddedEvent.getBlog().getProperties().get(COMMENT_PREFIX_IP);
          if (BlojsomUtils.checkNullOrBlank(emailPrefix)) {
            emailPrefix = DEFAULT_COMMENT_PREFIX;
          }

          email =
              (HtmlEmail) email.setSubject(emailPrefix + commentAddedEvent.getEntry().getTitle());

          email.send();
        } catch (EmailException e) {
          if (_logger.isErrorEnabled()) {
            _logger.error(e);
          }
        }
      } else {
        if (_logger.isErrorEnabled()) {
          _logger.error(
              "Missing SMTP servername servlet initialization parameter: "
                  + EmailConstants.SMTPSERVER_IP);
        }
      }
    }
  }
예제 #9
0
  protected boolean jmxRmiWebappNotification(
      String action, int version, String pathToWebapp, boolean isRecursive) {
    long start = System.currentTimeMillis();

    if (!verifyJmxRmiConnection()) {
      return false;
    }

    try {
      Boolean result =
          (Boolean)
              mbsc_.invoke(
                  virtWebappRegistry_,
                  action,
                  new Object[] {new Integer(version), pathToWebapp, new Boolean(isRecursive)},
                  new String[] {"java.lang.Integer", "java.lang.String", "java.lang.Boolean"});

      if (!result.booleanValue()) {
        if (log.isErrorEnabled())
          log.error(
              "Action failed: " + action + "  Version: " + version + "  Webapp: " + pathToWebapp);

        return false;
      }
      return true;
    } catch (Exception e) {
      if (log.isErrorEnabled())
        log.error(
            "Could not connect to JMX Server within remote "
                + "virtualization server "
                + "(this may be a transient error.)");

      closeJmxRmiConnection();

      return false;
    } finally {
      if (log.isDebugEnabled()) {
        log.debug(
            "jmxRmiWebappNotification: "
                + action
                + "["
                + version
                + ", "
                + pathToWebapp
                + ","
                + isRecursive
                + " in "
                + (System.currentTimeMillis() - start)
                + " ms");
      }
    }
  }
예제 #10
0
  public static int doWaitFor(Process p) {
    int exitValue = -1; // returned to caller when p is finished
    try {

      InputStream in = p.getInputStream();
      InputStream err = p.getErrorStream();
      boolean finished = false; // Set to true when p is finished

      while (!finished) {
        try {
          while (in.available() > 0) {
            // Print the output of our system call
            Character c = new Character((char) in.read());
            if (log.isDebugEnabled()) {
              log.debug(c);
            }
          }
          while (err.available() > 0) {
            // Print the output of our system call
            Character c = new Character((char) err.read());
            if (log.isDebugEnabled()) {
              log.debug(c);
            }
          }

          // Ask the process for its exitValue. If the process
          // is not finished, an IllegalThreadStateException
          // is thrown. If it is finished, we fall through and
          // the variable finished is set to true.
          exitValue = p.exitValue();
          finished = true;
        } catch (IllegalThreadStateException e) {
          Thread.currentThread();
          // Process is not finished yet;
          // Sleep a little to save on CPU cycles
          Thread.sleep(500);
        }
      }
    } catch (Exception e) {
      // unexpected exception! print it out for debugging...
      if (log.isErrorEnabled()) {
        log.error("doWaitFor(): unexpected exception - " + e.getMessage());
      }
      if (log.isErrorEnabled()) {
        log.error(e.getMessage());
      }
    }
    // return completion status to caller
    return exitValue;
  }
 /**
  * This returns the default SSL socket factory.
  *
  * @return <code>SocketFactory</code>
  */
 public static SocketFactory getDefault() {
   final LdapTLSSocketFactory sf = new LdapTLSSocketFactory();
   try {
     sf.initialize();
   } catch (IOException e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Error loading keystore", e);
     }
   } catch (GeneralSecurityException e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Error initializing socket factory", e);
     }
   }
   return sf;
 }
예제 #12
0
  /**
   * Returns the image resources of the gallery folder which are edited in the dialog form.
   *
   * <p>
   *
   * @return the images of the gallery folder which are edited in the dialog form
   */
  protected List getImages() {

    // get all image resources of the folder
    int imageId;
    try {
      imageId =
          OpenCms.getResourceManager()
              .getResourceType(CmsResourceTypeImage.getStaticTypeName())
              .getTypeId();
    } catch (CmsLoaderException e1) {
      // should really never happen
      LOG.warn(e1.getLocalizedMessage(), e1);
      imageId = CmsResourceTypeImage.getStaticTypeId();
    }
    CmsResourceFilter filter = CmsResourceFilter.IGNORE_EXPIRATION.addRequireType(imageId);
    try {
      return getCms().readResources(getParamResource(), filter, false);
    } catch (CmsException e) {
      // log, should never happen
      if (LOG.isErrorEnabled()) {
        LOG.error(e.getLocalizedMessage(getLocale()));
      }
      return new ArrayList(0);
    }
  }
예제 #13
0
  public boolean verifyJmxRmiConnection() {
    boolean result = false;

    // Typically the JMXServiceURL looks something like this:
    //  "service:jmx:rmi://ignored/jndi/rmi://localhost:50501/alfresco/jmxrmi"

    if (getVirtServerJmxUrl() == null) {
      if (log.isWarnEnabled()) log.warn("No virtualization servers have registered as listeners");

      return result;
    }

    if (conn_ == null) {
      try {
        conn_ = JMXConnectorFactory.connect(getJMXServiceURL(), env_);
        mbsc_ = conn_.getMBeanServerConnection();
      } catch (Exception e) {
        if (log.isErrorEnabled())
          log.error("Could not connect to virtualization server: " + getVirtServerJmxUrl());

        return result;
      }
    }
    // If virtualization server have been terminated (E.g. Control+C in the console)
    // virtServerJmxUrl_ is not null and conn_ is not null so it is impossible to detect
    // terminated/refused
    // connection. Just check connection to accessibility.
    else {
      result = pingVirtServer();
    }
    return result;
  }
  public void doExecute(@NotNull final AnActionEvent event, final Map<String, Object> _params) {
    try {
      NodeHighlightManager highlightManager =
          ((EditorComponent) MapSequence.fromMap(_params).get("editorComponent"))
              .getHighlightManager();
      EditorMessageOwner messageOwner =
          ((EditorComponent) MapSequence.fromMap(_params).get("editorComponent"))
              .getHighlightMessagesOwner();

      Set<SNode> usages =
          FindUsagesManager.getInstance()
              .findUsages(
                  Collections.singleton(
                      SNodeOperations.getConceptDeclaration(
                          ((SNode) MapSequence.fromMap(_params).get("node")))),
                  SearchType.INSTANCES,
                  new ModelsOnlyScope(
                      ((SModelDescriptor) MapSequence.fromMap(_params).get("model"))),
                  null);
      for (SNode ref : SetSequence.fromSet(usages)) {
        if (ref.getContainingRoot()
            == ((EditorComponent) MapSequence.fromMap(_params).get("editorComponent"))
                .getRootCell()
                .getSNode()
                .getContainingRoot()) {
          highlightManager.mark(ref, HighlightConstants.INSTANCES_COLOR, "usage", messageOwner);
        }
      }
      highlightManager.repaintAndRebuildEditorMessages();
    } catch (Throwable t) {
      if (log.isErrorEnabled()) {
        log.error("User's action execute method failed. Action:" + "HighlightInstances", t);
      }
    }
  }
예제 #15
0
 @Override
 public void error(Object message, Throwable t) {
   log.error(message, t);
   if (log.isErrorEnabled() && publisher != null) {
     publish(rosgraph_msgs.Log.ERROR, message, t);
   }
 }
  /**
   * @return SKIP_BODY
   * @see javax.servlet.jsp.tagext.Tag#doStartTag()
   */
  @Override
  public int doStartTag() throws JspException {

    ServletRequest req = pageContext.getRequest();

    // This will always be true if the page is called through OpenCms
    if (CmsFlexController.isCmsRequest(req)) {

      try {
        String setting = elementSettingTagAction(getName(), m_defaultValue, m_escapeHtml, req);
        // Make sure that no null String is returned
        if (setting == null) {
          setting = "";
        }
        pageContext.getOut().print(setting);

      } catch (Exception ex) {
        if (LOG.isErrorEnabled()) {
          LOG.error(
              Messages.get().getBundle().key(Messages.ERR_PROCESS_TAG_1, "elementSetting"), ex);
        }
        throw new javax.servlet.jsp.JspException(ex);
      }
    }
    return SKIP_BODY;
  }
  /**
   * Discover the content length and content type for an enclosure URL
   *
   * @param rssEnclosureURL URL for enclosure
   * @return String array containing the enclosure's content length and content type
   */
  protected String[] discoverEnclosureProperties(String rssEnclosureURL) {
    String[] enclosureProperties = new String[] {"", ""};

    try {
      if (!rssEnclosureURL.toLowerCase().startsWith("http://")) {
        if (_logger.isDebugEnabled()) {
          _logger.debug("RSS enclosure URL not an HTTP-accessible resource");
        }
      } else {
        URL enclosure = new URL(rssEnclosureURL);
        HttpURLConnection httpURLConnection = (HttpURLConnection) enclosure.openConnection();
        httpURLConnection.setRequestMethod("HEAD");
        httpURLConnection.connect();

        enclosureProperties[0] = Integer.toString(httpURLConnection.getContentLength());
        enclosureProperties[1] = httpURLConnection.getContentType();

        httpURLConnection.disconnect();
      }
    } catch (Exception e) {
      if (_logger.isErrorEnabled()) {
        _logger.error("Error retrieving enclosure properties", e);
      }
    }

    return enclosureProperties;
  }
 @ExceptionHandler(value = Exception.class)
 public void onException(Exception e, HttpServletResponse response) {
   response.setStatus(404);
   if (log.isErrorEnabled()) {
     log.error("Fehler beim Rendern eines der Javascript Konfiguration.", e);
   }
 }
 void save() {
   try {
     preferences.store();
   } catch (final Exception e) {
     if (logger.isErrorEnabled()) logger.error(e);
   }
 }
예제 #20
0
  /** Set executor service and invoke execute() method to start the load balancer extension. */
  public void execute() {
    try {
      if (log.isInfoEnabled()) {
        log.info("Load balancer extension started");
      }

      // Start topology receiver thread
      startTopologyEventReceiver(executorService, topologyProvider);
      startApplicationEventReceiver(executorService);
      startApplicationSignUpEventReceiver(executorService, topologyProvider);
      startDomainMappingEventReceiver(executorService, topologyProvider);

      if (statsReader != null) {
        // Start stats notifier thread
        statisticsNotifier = new LoadBalancerStatisticsNotifier(statsReader, topologyProvider);
        Thread statsNotifierThread = new Thread(statisticsNotifier);
        statsNotifierThread.start();
      } else {
        if (log.isWarnEnabled()) {
          log.warn("Load balancer statistics reader not found");
        }
      }
      log.info("Waiting for complete topology event...");
    } catch (Exception e) {
      if (log.isErrorEnabled()) {
        log.error("Could not start load balancer extension", e);
      }
    }
  }
  // Check the decorated log instance
  protected void checkDecorated() {

    assertNotNull("Log exists", log);
    assertEquals(
        "Log class",
        "org.apache.commons.logging.simple.DecoratedSimpleLog",
        log.getClass().getName());

    // Can we call level checkers with no exceptions?
    assertTrue(!log.isDebugEnabled());
    assertTrue(log.isErrorEnabled());
    assertTrue(log.isFatalEnabled());
    assertTrue(log.isInfoEnabled());
    assertTrue(!log.isTraceEnabled());
    assertTrue(log.isWarnEnabled());

    // Can we retrieve the current log level?
    assertEquals(SimpleLog.LOG_LEVEL_INFO, ((SimpleLog) log).getLevel());

    // Can we validate the extra exposed properties?
    assertEquals("yyyy/MM/dd HH:mm:ss:SSS zzz", ((DecoratedSimpleLog) log).getDateTimeFormat());
    assertEquals("DecoratedLogger", ((DecoratedSimpleLog) log).getLogName());
    assertTrue(!((DecoratedSimpleLog) log).getShowDateTime());
    assertTrue(((DecoratedSimpleLog) log).getShowShortName());
  }
  /**
   * @see org.opencms.frontend.layoutpage.I_CmsMacroWrapper#getResult(java.lang.String,
   *     java.lang.String[])
   */
  public String getResult(String macroName, String[] args) {

    Writer out = new StringWriter();
    boolean error = false;
    try {
      // get the macro object to process
      Macro macro = (Macro) m_template.getMacros().get(macroName);
      if (macro != null) {
        // found macro, put it context
        putContextVariable(MACRO_NAME, macro);
        // process the template
        m_template.process(getContext(), out);
      } else {
        // did not find macro
        error = true;
      }
    } catch (Exception e) {
      if (LOG.isErrorEnabled()) {
        LOG.error(e.getLocalizedMessage(), e);
      }
      error = true;
    } finally {
      try {
        out.close();
      } catch (Exception e) {
        // ignore exception when closing writer
      }
    }
    if (error) {
      return "";
    }
    return out.toString();
  }
 void setProperty(final String key, final Object value) {
   try {
     if (!preferences.isReadOnly(key)) preferences.setValue(key, value.toString());
   } catch (final ReadOnlyException e) {
     if (logger.isErrorEnabled()) logger.error(e);
   }
 }
  @Override
  protected void doJob() throws Exception {
    //		log.debug("doJob()");
    temperatureBufferBlockMap.allocate();

    boolean localHalt = shouldHalt;

    while (!localHalt) {
      try {
        jobsToDoSemaphore.acquire();
        jobsToDoSemaphore.drainPermits();
        if (SampleCache.DEBUG_SAMPLE_CACHE_ACTIVITY) {
          log.trace("Attempting to refresh cache.");
        }
        sampleCache.refreshCache();
      } catch (final InterruptedException ie) {
        // Don't care, probably woken up to shutdown
      } catch (final Exception e) {
        if (log.isErrorEnabled()) {
          log.error("Exception caught during cache population run: " + e.toString(), e);
        }
      }
      localHalt = shouldHalt;
    }
  }
  public void doExecute(@NotNull final AnActionEvent event, final Map<String, Object> _params) {
    try {
      SNodePointer script =
          new SNodePointer(
              "r:00000000-0000-4000-0000-011c89590367(jetbrains.mps.lang.plugin.scripts)",
              "4214874532454943783");

      MigrationScriptExecutor executor =
          new MigrationScriptExecutor(
              script,
              "Resolve Broken Stub References",
              ((IOperationContext) MapSequence.fromMap(_params).get("context")),
              ((Project) MapSequence.fromMap(_params).get("project")));
      if (CommandProcessorEx.getInstance().getCurrentCommand() != null) {
        executor.execImmediately(new ProgressMonitorAdapter(new EmptyProgressIndicator()));
      } else {
        executor.execAsCommand(((Frame) MapSequence.fromMap(_params).get("frame")));
      }
    } catch (Throwable t) {
      if (log.isErrorEnabled()) {
        log.error(
            "User's action execute method failed. Action:" + "MigrationScript_ResolveBrokenRefs",
            t);
      }
    }
  }
  /**
   * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (!initParams.getEnabled()) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    long startTime = 0;
    if (logger.isTraceEnabled()) {
      startTime = System.currentTimeMillis();
    }

    FileFilterMode.setClient(Client.webdav);

    try {
      // Create the appropriate WebDAV method for the request and execute it
      final WebDAVMethod method = createMethod(request, response);

      if (method == null) {
        if (logger.isErrorEnabled())
          logger.error("WebDAV method not implemented - " + request.getMethod());

        // Return an error status

        response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
        return;
      } else if (method.getRootNodeRef() == null) {
        if (logger.isDebugEnabled()) {
          logger.debug(
              "No root node for request ["
                  + request.getMethod()
                  + " "
                  + request.getRequestURI()
                  + "]");
        }

        // Return an error status
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
      }

      // Execute the WebDAV request, which must take care of its own transaction
      method.execute();
    } catch (Throwable e) {
      ExceptionHandler exHandler = new ExceptionHandler(e, request, response);
      exHandler.handle();
    } finally {
      if (logger.isTraceEnabled()) {
        logger.trace(
            request.getMethod()
                + " took "
                + (System.currentTimeMillis() - startTime)
                + "ms to execute ["
                + request.getRequestURI()
                + "]");
      }

      FileFilterMode.clearClient();
    }
  }
  protected void okPressed() {
    boolean hasErrors = popupValidationErrorDialogIfNecessary();

    if (!hasErrors) {
      try {
        conceptUtil.setId(wId.getText());
      } catch (ObjectAlreadyExistsException e) {
        if (logger.isErrorEnabled()) {
          logger.error("an exception occurred", e);
        }
        MessageDialog.openError(
            getShell(),
            Messages.getString("General.USER_TITLE_ERROR"),
            Messages.getString(
                "PhysicalTableDialog.USER_ERROR_PHYSICAL_TABLE_ID_EXISTS", wId.getText()));
        return;
      }

      // attempt to set the connection
      IStructuredSelection selection = (IStructuredSelection) comboViewer.getSelection();
      DatabaseMeta con = (DatabaseMeta) selection.getFirstElement();
      BusinessModel busModel = (BusinessModel) conceptUtil;
      if (!DUMMY_CON_NAME.equals(con.getName())) {
        busModel.setConnection((DatabaseMeta) con);
      } else {
        busModel.clearConnection();
      }

      super.okPressed();
    }
  }
예제 #28
0
 public static void createAndAddToRepository(List<Object> properties, Repository repository)
     throws RepositoryException {
   if (ExperianUtils.experianRequestItemProperties.size() != properties.size()) {
     StringBuffer sb = new StringBuffer("Incorrect size of list. List must have size = ");
     sb.append(ExperianUtils.experianRequestItemProperties.size());
     sb.append(", but not ");
     sb.append(properties.size());
     sb.append(".");
     throw new RuntimeException(sb.toString());
   }
   ;
   MutableRepositoryItem mri = ((MutableRepository) repository).createItem("experianRequest");
   Iterator<String> it = ExperianUtils.experianRequestItemProperties.keySet().iterator();
   int i = 0;
   while (it.hasNext()) {
     try {
       String temp = it.next();
       mri.setPropertyValue(temp, properties.get(i));
       // throw new NullPointerException("Test exception");
     } catch (Exception ex) {
       if (LOGGER.isErrorEnabled()) {
         LOGGER.error(ex);
       }
     }
     i++;
   }
   ((MutableRepository) repository).addItem(mri);
 }
예제 #29
0
  public synchronized NetworkStatsItemBean[] getSearchItems() {
    if (null == queryString) {
      return null;
    }
    if (!isFreshSearch) {
      return searchItemBeans;
    }

    try {
      ItemType searchItems[] = getSearchResults(queryString);
      if (null == searchItems) {
        return null;
      }
      searchItemBeans = new NetworkStatsItemBean[searchItems.length];

      for (int i = 0; i < searchItems.length; i++) {
        searchItemBeans[i] = new NetworkStatsItemBean(searchItems[i]);
      }
      isFreshSearch = false;
      Thread t = new Thread(new NetworkStatsItemDetailer(this, searchItemBeans));
      t.start();
      return searchItemBeans;
    } catch (Exception e) {
      if (log.isErrorEnabled()) {
        log.error("Failed to read the available search items because of " + e);
      }
    }
    return null;
  }
  /**
   * Process the blog entries
   *
   * @param httpServletRequest Request
   * @param httpServletResponse Response
   * @param blog {@link Blog} instance
   * @param context Context
   * @param entries Blog entries retrieved for the particular request
   * @return Modified set of blog entries
   * @throws PluginException If there is an error processing the blog entries
   */
  public Entry[] process(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      Blog blog,
      Map context,
      Entry[] entries)
      throws PluginException {
    Map entriesPerCategory = new HashMap();

    try {
      Category[] categories = (Category[]) context.get(BlojsomConstants.BLOJSOM_ALL_CATEGORIES);
      if (categories != null && categories.length > 0) {
        for (int i = 0; i < categories.length; i++) {
          Category category = categories[i];
          entriesPerCategory.put(
              category.getId(), _fetcher.countEntriesForCategory(blog, category));
        }
      }
    } catch (FetcherException e) {
      if (_logger.isErrorEnabled()) {
        _logger.error(e);
      }
    }

    context.put(PLUGIN_CONTEXT_ENTRIES_PER_CATEGORY, entriesPerCategory);

    return entries;
  }