コード例 #1
0
ファイル: MailUtil.java プロジェクト: yyyfan/xkg
 public boolean send() {
   try {
     MimeMessage msg = javaMailSender.createMimeMessage();
     MimeMessageHelper message = new MimeMessageHelper(msg, true, "UTF-8");
     message.setFrom(from);
     message.setSubject(title);
     message.setTo(toEmails);
     message.setText(getMessage(), true); // 如果发的不是html内容去掉true参数��
     // message.addInline("myLogo",new ClassPathResource("img/mylogo.gif"));
     // message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf"));
     javaMailSender.send(msg);
   } catch (MessagingException e) {
     e.printStackTrace();
     if (log.isWarnEnabled()) {
       log.warn("邮件信息导常! 邮件标题为: " + title);
     }
     return false;
   } catch (MailException me) {
     me.printStackTrace();
     if (log.isWarnEnabled()) {
       log.warn("发送邮件失败! 邮件标题为: " + title);
     }
     return false;
   }
   return true;
 }
コード例 #2
0
  /**
   * Called immediately after an element has been put into the cache and the element already existed
   * in the cache. This is thus an update.
   *
   * <p>The {@link net.sf.ehcache.Cache#put(net.sf.ehcache.Element)} method will block until this
   * method returns.
   *
   * <p>Implementers may wish to have access to the Element's fields, including value, so the
   * element is provided. Implementers should be careful not to modify the element. The effect of
   * any modifications is undefined.
   *
   * @param cache the cache emitting the notification
   * @param element the element which was just put into the cache.
   */
  public final void notifyElementUpdated(final Ehcache cache, final Element element)
      throws CacheException {
    if (notAlive()) {
      return;
    }
    if (!replicateUpdates) {
      return;
    }

    if (replicateUpdatesViaCopy) {
      if (!element.isSerializable()) {
        if (LOG.isWarnEnabled()) {
          LOG.warn(
              "Object with key "
                  + element.getObjectKey()
                  + " is not Serializable and cannot be updated via copy");
        }
        return;
      }
      addToReplicationQueue(new CacheEventMessage(EventMessage.PUT, cache, element, null));
    } else {
      if (!element.isKeySerializable()) {
        if (LOG.isWarnEnabled()) {
          LOG.warn(
              "Key " + element.getObjectKey() + " is not Serializable and cannot be replicated.");
        }
        return;
      }
      addToReplicationQueue(
          new CacheEventMessage(EventMessage.REMOVE, cache, null, element.getKey()));
    }
  }
コード例 #3
0
  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) {
        }
      }
    }
  }
コード例 #4
0
  protected static void init(SCSession session, Class<? extends SCKeynodesBase> klass) {
    if (log.isDebugEnabled()) log.debug("Start retrieving keynodes for " + klass);

    try {
      //
      // Search default segment for keynodes
      //
      SCSegment defaultSegment = null;
      {
        DefaultSegment annotation = klass.getAnnotation(DefaultSegment.class);
        if (annotation != null) {
          defaultSegment = session.openSegment(annotation.value());
          Validate.notNull(defaultSegment, "Default segment \"{0}\" not found", annotation.value());
          klass.getField(annotation.fieldName()).set(null, defaultSegment);
        }
      }

      Field[] fields = klass.getFields();
      for (Field field : fields) {
        int modifiers = field.getModifiers();

        if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
          Class<?> type = field.getType();
          if (type.equals(SCSegment.class)) {
            //
            // We have segment field. Load segment by uri.
            //
            SegmentURI annotation = field.getAnnotation(SegmentURI.class);

            if (annotation != null) {
              String uri = annotation.value();
              SCSegment segment = session.openSegment(uri);
              field.set(null, segment);
            } else {
              // May be it already has value?
              if (log.isWarnEnabled()) {
                if (field.get(null) == null) log.warn(field + " doesn't have value");
              }
            }
          } else {
            if (!(checkKeynode(session, defaultSegment, field)
                || checkKeynodeURI(session, field)
                || checkKeynodesNumberPatternURI(session, klass, field))) {

              if (log.isWarnEnabled()) {
                if (field.get(null) == null)
                  log.warn(field + " doesn't have annotations and value");
              }
            }
          }
        }
      }
    } catch (Exception e) {
      // TODO: handle
      e.printStackTrace();
    }
  }
コード例 #5
0
  private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements =
        new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {
      LinkedList<InjectionMetadata.InjectedElement> currElements =
          new LinkedList<InjectionMetadata.InjectedElement>();
      for (Field field : targetClass.getDeclaredFields()) {
        Annotation annotation = findAutowiredAnnotation(field);
        if (annotation != null) {
          if (Modifier.isStatic(field.getModifiers())) {
            if (logger.isWarnEnabled()) {
              logger.warn("Autowired annotation is not supported on static fields: " + field);
            }
            continue;
          }
          boolean required = determineRequiredStatus(annotation);
          currElements.add(new AutowiredFieldElement(field, required));
        }
      }
      for (Method method : targetClass.getDeclaredMethods()) {
        Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
        Annotation annotation =
            BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)
                ? findAutowiredAnnotation(bridgedMethod)
                : findAutowiredAnnotation(method);
        if (annotation != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
          if (Modifier.isStatic(method.getModifiers())) {
            if (logger.isWarnEnabled()) {
              logger.warn("Autowired annotation is not supported on static methods: " + method);
            }
            continue;
          }
          if (method.getParameterTypes().length == 0) {
            if (logger.isWarnEnabled()) {
              logger.warn(
                  "Autowired annotation should be used on methods with actual parameters: "
                      + method);
            }
          }
          boolean required = determineRequiredStatus(annotation);
          PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method);
          currElements.add(new AutowiredMethodElement(method, required, pd));
        }
      }
      elements.addAll(0, currElements);
      targetClass = targetClass.getSuperclass();
    } while (targetClass != null && targetClass != Object.class);

    return new InjectionMetadata(clazz, elements);
  }
コード例 #6
0
  @Override
  public void commit() {

    if (txLogger.isInfoEnabled()) {
      txLogger.info("commit");
    }

    ThreadContext.Context ctx = ThreadContext.getContext(this.metaData.getName());

    if (ctx == null) {
      if (txLogger.isWarnEnabled()) {
        txLogger.warn("ignoring commit - no tx in progress");
        if (txLogger.isDebugEnabled()) {
          logStackTrace();
        }
      }
      return;
    }

    TransactionStatus txStatus = ctx.getTransactionStatus();

    try {
      if (txStatus == null) {
        if (txLogger.isWarnEnabled()) {
          txLogger.warn("ignoring commit - no tx status");
          if (txLogger.isDebugEnabled()) {
            logStackTrace();
          }
        }
      } else {
        this.txMgr.commit(txStatus);
      }
    } finally {
      ctx.setTransactionStatus(null);
      ThreadContext.unsetContext(this.metaData.getName());
      HashMap<String, ThreadContext.Context> contextHash = ThreadContext.getThreadLocalHash();

      if (contextHash != null && contextHash.size() > 0) {
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
          TransactionSynchronizationManager.initSynchronization();
        }
      } else {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
          TransactionSynchronizationManager.clear();
          Map map = TransactionSynchronizationManager.getResourceMap();
          for (Object entry : map.keySet()) {
            TransactionSynchronizationManager.unbindResource(entry);
          }
        }
      }
    }
  }
コード例 #7
0
  /**
   * Identify the version. Should only need to be invoked once.
   *
   * @return the version or null if it cannot be identified
   */
  @Override
  public String identifyVersion() {
    String version = null;
    String path = format(POM_CLASSPATH_FORMAT, groupId, artifactId);
    InputStream is = resolveClassloader.getResourceAsStream(path);

    if (is == null && applicationContext != null) {
      // Not found on classpath
      Resource resource = applicationContext.getResource(path);
      if (resource != null) {
        try {
          is = resource.getInputStream();
        } catch (IOException e) {
          if (log.isWarnEnabled()) {
            log.warn(
                format(
                    "Failed to load 'pom.properties' from application "
                        + "context for group '%s', artifact '%s'.",
                    groupId, artifactId));
          }
        }
      }
    }

    if (is != null) {
      Properties props = new Properties();
      try {
        props.load(is);
        version = props.getProperty(POM_PROPS_VERSION);
      } catch (IOException e) {
        if (log.isWarnEnabled()) {
          log.warn(
              format(
                  "Failed to load 'pom.properties' from classpath for group '%s', artifact '%s'. "
                      + "No version will be included in the resource file names.",
                  groupId, artifactId));
        }
      } finally {
        closeQuietly(is);
      }
    } else {
      if (log.isWarnEnabled()) {
        log.warn(
            format(
                "Unable to locate 'pom.properties' for group '%s', artifact '%s'. "
                    + "No version will be included in the resource file names.",
                groupId, artifactId));
      }
    }
    return version;
  }
コード例 #8
0
  /**
   * Handle a Magnet request via a socket (for TCP handling). Deiconify the application, fire MAGNET
   * request and return true as a sign that LimeWire is running.
   */
  public void fireControlThread(Socket socket, boolean magnet) {
    LOG.trace("enter fireControl");

    Thread.currentThread().setName("IncomingControlThread");
    try {
      // Only allow control from localhost
      if (!NetworkUtils.isLocalHost(socket)) {
        if (LOG.isWarnEnabled())
          LOG.warn("Invalid control request from: " + socket.getInetAddress().getHostAddress());
        return;
      }

      // First read extra parameter
      socket.setSoTimeout(Constants.TIMEOUT);
      ByteReader br = new ByteReader(socket.getInputStream());
      // read the first line. if null, throw an exception
      String line = br.readLine();
      socket.setSoTimeout(0);

      BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
      String s = CommonUtils.getUserName() + "\r\n";
      // system internal, so use system encoding
      byte[] bytes = s.getBytes();
      out.write(bytes);
      out.flush();
      if (magnet) handleMagnetRequest(line);
      else handleTorrentRequest(line);
    } catch (IOException e) {
      LOG.warn("Exception while responding to control request", e);
    } finally {
      IOUtils.close(socket);
    }
  }
コード例 #9
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;
  }
コード例 #10
0
ファイル: Mimetypes.java プロジェクト: fjzwxh/bce-sdk-java
  /** Loads MIME type info from the file 'mime.types' in the classpath, if it's available. */
  public static synchronized Mimetypes getInstance() {
    if (mimetypes != null) {
      return mimetypes;
    }

    mimetypes = new Mimetypes();
    InputStream is = mimetypes.getClass().getResourceAsStream("/mime.types");
    if (is != null) {
      if (log.isDebugEnabled()) {
        log.debug("Loading mime types from file in the classpath: mime.types");
      }
      try {
        mimetypes.loadAndReplaceMimetypes(is);
      } catch (IOException e) {
        if (log.isErrorEnabled()) {
          log.error("Failed to load mime types from file in the classpath: mime.types", e);
        }
      } finally {
        try {
          is.close();
        } catch (IOException ex) {
          log.debug("", ex);
        }
      }
    } else {
      if (log.isWarnEnabled()) {
        log.warn("Unable to find 'mime.types' file in classpath");
      }
    }
    return mimetypes;
  }
コード例 #11
0
 @Override
 public void warn(Object message, Throwable t) {
   log.warn(message, t);
   if (log.isWarnEnabled() && publisher != null) {
     publish(rosgraph_msgs.Log.WARN, message, t);
   }
 }
コード例 #12
0
  public PmlEdmLevelSend remove(int levelSendId)
      throws NoSuchPmlEdmLevelSendException, SystemException {
    Session session = null;

    try {
      session = openSession();

      PmlEdmLevelSend pmlEdmLevelSend =
          (PmlEdmLevelSend) session.get(PmlEdmLevelSendImpl.class, new Integer(levelSendId));

      if (pmlEdmLevelSend == null) {
        if (_log.isWarnEnabled()) {
          _log.warn("No PmlEdmLevelSend exists with the primary key " + levelSendId);
        }

        throw new NoSuchPmlEdmLevelSendException(
            "No PmlEdmLevelSend exists with the primary key " + levelSendId);
      }

      return remove(pmlEdmLevelSend);
    } catch (NoSuchPmlEdmLevelSendException nsee) {
      throw nsee;
    } catch (Exception e) {
      throw processException(e);
    } finally {
      closeSession(session);
    }
  }
コード例 #13
0
ファイル: LibraryManagerImpl.java プロジェクト: novr/mayaa
 protected void warnAlreadyRegistered(PositionAware obj, String name, int index) {
   if (LOG.isWarnEnabled()) {
     String systemID = obj.getSystemID();
     String lineNumber = Integer.toString(obj.getLineNumber());
     LOG.warn(StringUtil.getMessage(LibraryManagerImpl.class, index, name, systemID, lineNumber));
   }
 }
コード例 #14
0
 /**
  * This returns a keystore as an <code>InputStream</code>. If the keystore could not be loaded
  * this method returns null.
  *
  * @param filename <code>String</code> to read
  * @param pt <code>PathType</code> how to read file
  * @return <code>InputStream</code> keystore
  */
 private InputStream getInputStream(final String filename, final PathType pt) {
   InputStream is = null;
   if (pt == PathType.CLASSPATH) {
     is = LdapTLSSocketFactory.class.getResourceAsStream(filename);
   } else if (pt == PathType.FILEPATH) {
     File file;
     try {
       file = new File(URI.create(filename));
     } catch (IllegalArgumentException e) {
       file = new File(filename);
     }
     try {
       is = new FileInputStream(file);
     } catch (IOException e) {
       if (LOG.isWarnEnabled()) {
         LOG.warn("Error loading keystore from " + filename, e);
       }
     }
   }
   if (is != null) {
     if (LOG.isDebugEnabled()) {
       LOG.debug("Successfully loaded " + filename + " from " + pt);
     }
   } else {
     if (LOG.isDebugEnabled()) {
       LOG.debug("Failed to load " + filename + " from " + pt);
     }
   }
   return is;
 }
コード例 #15
0
  public int compare(Object o1, Object o2) {
    Object v1 = getPropertyValue(o1);
    Object v2 = getPropertyValue(o2);
    if (this.sortDefinition.isIgnoreCase() && (v1 instanceof String) && (v2 instanceof String)) {
      v1 = ((String) v1).toLowerCase();
      v2 = ((String) v2).toLowerCase();
    }

    int result;

    // Put an object with null property at the end of the sort result.
    try {
      if (v1 != null) {
        result = (v2 != null ? ((Comparable) v1).compareTo(v2) : -1);
      } else {
        result = (v2 != null ? 1 : 0);
      }
    } catch (RuntimeException ex) {
      if (logger.isWarnEnabled()) {
        logger.warn("Could not sort objects [" + o1 + "] and [" + o2 + "]", ex);
      }
      return 0;
    }

    return (this.sortDefinition.isAscending() ? result : -result);
  }
コード例 #16
0
  /**
   * Get the {@link PlatformTransactionManager transaction manager} to use for the supplied {@link
   * TestContext test context} and {@code qualifier}.
   *
   * <p>Delegates to {@link #getTransactionManager(TestContext)} if the supplied {@code qualifier}
   * is {@code null} or empty.
   *
   * @param testContext the test context for which the transaction manager should be retrieved
   * @param qualifier the qualifier for selecting between multiple bean matches; may be {@code null}
   *     or empty
   * @return the transaction manager to use, or {@code null} if not found
   * @throws BeansException if an error occurs while retrieving the transaction manager
   * @see #getTransactionManager(TestContext)
   */
  protected final PlatformTransactionManager getTransactionManager(
      TestContext testContext, String qualifier) {
    // look up by type and qualifier from @Transactional
    if (StringUtils.hasText(qualifier)) {
      try {
        // Use autowire-capable factory in order to support extended qualifier
        // matching (only exposed on the internal BeanFactory, not on the
        // ApplicationContext).
        BeanFactory bf = testContext.getApplicationContext().getAutowireCapableBeanFactory();

        return BeanFactoryAnnotationUtils.qualifiedBeanOfType(
            bf, PlatformTransactionManager.class, qualifier);
      } catch (RuntimeException ex) {
        if (logger.isWarnEnabled()) {
          logger.warn(
              "Caught exception while retrieving transaction manager for test context "
                  + testContext
                  + " and qualifier ["
                  + qualifier
                  + "]",
              ex);
        }
        throw ex;
      }
    }

    // else
    return getTransactionManager(testContext);
  }
コード例 #17
0
ファイル: JobManager.java プロジェクト: gspandy/beatles
  // 重置在指定时间内未完成的任务
  protected void checkTaskStatus() {
    Iterator<String> taskIds = statusPool.keySet().iterator();

    while (taskIds.hasNext()) {
      String taskId = taskIds.next();

      JobTaskStatus taskStatus = statusPool.get(taskId);
      JobTask jobTask = jobTaskPool.get(taskId);

      if (taskStatus == JobTaskStatus.DOING
          && jobTask.getStartTime() != 0
          && System.currentTimeMillis() - jobTask.getStartTime()
              >= jobTask.getTaskRecycleTime() * 1000) {
        if (statusPool.replace(taskId, JobTaskStatus.DOING, JobTaskStatus.UNDO)) {
          jobTask.setStatus(JobTaskStatus.UNDO);
          undoTaskQueue.offer(jobTask);
          jobTask.getRecycleCounter().incrementAndGet();

          if (logger.isWarnEnabled())
            logger.warn(
                "Task : " + jobTask.getTaskId() + " can't complete in time, it be recycle.");
        }
      }
    }
  }
コード例 #18
0
 @ScriptMethod(
     help = "Returns true if warn logging is enabled.",
     code = "var loggerStatus = logger.isWarnLogginEnabled();",
     output = "true if warn logging is enabled")
 public boolean isWarnLoggingEnabled() {
   return logger.isWarnEnabled();
 }
 /**
  * Once the job has been filled with {@link DomainConfiguration}s, performs the following
  * operations:
  *
  * <ol>
  *   <li>Edit the harvest template to add/remove deduplicator configuration.
  *   <li>
  * </ol>
  *
  * @param job the job
  */
 protected void editJobOrderXml(Job job) {
   Document doc = job.getOrderXMLdoc();
   if (DEDUPLICATION_ENABLED) {
     // Check that the Deduplicator element is present in the
     // OrderXMl and enabled. If missing or disabled log a warning
     if (!HeritrixTemplate.isDeduplicationEnabledInTemplate(doc)) {
       if (log.isWarnEnabled()) {
         log.warn(
             "Unable to perform deduplication for this job"
                 + " as the required DeDuplicator element is "
                 + "disabled or missing from template");
       }
     }
   } else {
     // Remove deduplicator Element from OrderXML if present
     Node xpathNode = doc.selectSingleNode(HeritrixTemplate.DEDUPLICATOR_XPATH);
     if (xpathNode != null) {
       xpathNode.detach();
       job.setOrderXMLDoc(doc);
       if (log.isInfoEnabled()) {
         log.info("Removed DeDuplicator element because " + "Deduplication is disabled");
       }
     }
   }
 }
コード例 #20
0
ファイル: CasDoctor.java プロジェクト: jianlins/webanno
 public void repair(CAS aCas) {
   List<LogMessage> messages = new ArrayList<>();
   repair(aCas, messages);
   if (log.isWarnEnabled() && !messages.isEmpty()) {
     messages.forEach(s -> log.warn(s));
   }
 }
コード例 #21
0
  public void initialize() {
    Properties passwordProps = new Properties();
    String jmxrmi_password = null;

    try {
      // throws exception when there's no password file to be found.
      InputStream is = new FileInputStream(passwordFile_);
      try {
        passwordProps.load(is);
      } finally {
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
          }
        }
      }

      jmxrmi_password = passwordProps.getProperty("controlRole");
      env_ = new HashMap<String, Object>();
      String[] cred = new String[] {"controlRole", jmxrmi_password};
      env_.put("jmx.remote.credentials", cred);
      virtWebappRegistry_ =
          ObjectName.getInstance("Alfresco:Name=VirtWebappRegistry,Type=VirtWebappRegistry");
    } catch (Exception e) {
      if (log.isWarnEnabled()) {
        log.warn(
            "WCM virtualization disabled "
                + "(alfresco-jmxrmi.password and/or "
                + "alfresco-jmxrmi.access isn't on classpath) due to: "
                + e);
      }
    }
  }
コード例 #22
0
  /**
   * If the existing proxy is insufficiently "narrow" (derived), instantiate a new proxy and
   * overwrite the registration of the old one. This breaks == and occurs only for "class" proxies
   * rather than "interface" proxies. Also init the proxy to point to the given target
   * implementation if necessary.
   *
   * @param proxy The proxy instance to be narrowed.
   * @param persister The persister for the proxied entity.
   * @param key The internal cache key for the proxied entity.
   * @param object (optional) the actual proxied entity instance.
   * @return An appropriately narrowed instance.
   * @throws HibernateException
   */
  public Object narrowProxy(Object proxy, EntityPersister persister, EntityKey key, Object object)
      throws HibernateException {

    boolean alreadyNarrow =
        persister.getConcreteProxyClass(session.getEntityMode()).isAssignableFrom(proxy.getClass());

    if (!alreadyNarrow) {
      if (PROXY_WARN_LOG.isWarnEnabled()) {
        PROXY_WARN_LOG.warn(
            "Narrowing proxy to "
                + persister.getConcreteProxyClass(session.getEntityMode())
                + " - this operation breaks ==");
      }

      if (object != null) {
        proxiesByKey.remove(key);
        return object; // return the proxied object
      } else {
        proxy = persister.createProxy(key.getIdentifier(), session);
        proxiesByKey.put(key, proxy); // overwrite old proxy
        return proxy;
      }

    } else {

      if (object != null) {
        LazyInitializer li = ((HibernateProxy) proxy).getHibernateLazyInitializer();
        li.setImplementation(object);
      }

      return proxy;
    }
  }
コード例 #23
0
  // 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());
  }
コード例 #24
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);
      }
    }
  }
コード例 #25
0
  public SoPhongVanBanNoiBo remove(SoPhongVanBanNoiBoPK soPhongVanBanNoiBoPK)
      throws NoSuchSoPhongVanBanNoiBoException, SystemException {
    Session session = null;

    try {
      session = openSession();

      SoPhongVanBanNoiBo soPhongVanBanNoiBo =
          (SoPhongVanBanNoiBo) session.get(SoPhongVanBanNoiBoImpl.class, soPhongVanBanNoiBoPK);

      if (soPhongVanBanNoiBo == null) {
        if (_log.isWarnEnabled()) {
          _log.warn("No SoPhongVanBanNoiBo exists with the primary key " + soPhongVanBanNoiBoPK);
        }

        throw new NoSuchSoPhongVanBanNoiBoException(
            "No SoPhongVanBanNoiBo exists with the primary key " + soPhongVanBanNoiBoPK);
      }

      return remove(soPhongVanBanNoiBo);
    } catch (NoSuchSoPhongVanBanNoiBoException nsee) {
      throw nsee;
    } catch (Exception e) {
      throw processException(e);
    } finally {
      closeSession(session);
    }
  }
コード例 #26
0
 public Template createTemplateForUri(String[] uri) {
   Template t;
   if (!isReloadEnabled()) {
     for (String anUri : uri) {
       t = createTemplateFromPrecompiled(anUri);
       if (t != null) {
         return t;
       }
     }
   }
   Resource resource = null;
   for (String anUri : uri) {
     Resource r = getResourceForUri(anUri);
     if (r.exists()) {
       resource = r;
       break;
     }
   }
   if (resource != null) {
     if (precompiledGspMap != null && precompiledGspMap.size() > 0) {
       if (LOG.isWarnEnabled()) {
         LOG.warn(
             "Precompiled GSP not found for uri: "
                 + Arrays.asList(uri)
                 + ". Using resource "
                 + resource);
       }
     }
     return createTemplate(resource);
   }
   return null;
 }
コード例 #27
0
ファイル: ManejadorRoles.java プロジェクト: Glpz/Mantto2016
  public int crearRol(Rol rol) {

    int resultado;

    if (log.isDebugEnabled()) {
      log.debug(">guardarRol(rol)");
    }

    try {
      HibernateUtil.beginTransaction();

      if (dao.existeRol(rol.getNombre())) {
        resultado = 1; // Excepción. El nombre de rol ya existe
      } else {

        dao.hazPersistente(rol);

        resultado = 0; // Exito. El rol se creo satisfactoriamente.
      }

      HibernateUtil.commitTransaction();

    } catch (ExcepcionInfraestructura e) {
      HibernateUtil.rollbackTransaction();

      if (log.isWarnEnabled()) {
        log.warn("<ExcepcionInfraestructura");
      }
      resultado = 2; // Excepción. Falla en la infraestructura
    } finally {
      HibernateUtil.closeSession();
    }
    return resultado;
  }
コード例 #28
0
  public LogVanBanNoiBo remove(long logVanBanNoiBoId)
      throws NoSuchLogVanBanNoiBoException, SystemException {
    Session session = null;

    try {
      session = openSession();

      LogVanBanNoiBo logVanBanNoiBo =
          (LogVanBanNoiBo) session.get(LogVanBanNoiBoImpl.class, new Long(logVanBanNoiBoId));

      if (logVanBanNoiBo == null) {
        if (_log.isWarnEnabled()) {
          _log.warn("No LogVanBanNoiBo exists with the primary key " + logVanBanNoiBoId);
        }

        throw new NoSuchLogVanBanNoiBoException(
            "No LogVanBanNoiBo exists with the primary key " + logVanBanNoiBoId);
      }

      return remove(logVanBanNoiBo);
    } catch (NoSuchLogVanBanNoiBoException nsee) {
      throw nsee;
    } catch (Exception e) {
      throw processException(e);
    } finally {
      closeSession(session);
    }
  }
コード例 #29
0
  private void source(Interpreter interpreter) {
    for (IConfigurationElement config :
        getExtensionInfo("org.jactr.tools.shell.commands", "source")) {
      String url = config.getAttribute("url");
      String resource = config.getAttribute("resource");
      URL actualURL = null;

      if (resource != null) actualURL = getClass().getClassLoader().getResource(resource);
      else if (url != null)
        try {
          actualURL = new URL(url);
        } catch (Exception e) {
          if (LOGGER.isWarnEnabled()) LOGGER.warn(url + " is not a valid url ", e);
        }

      if (actualURL != null)
        try {
          interpreter.set("tmpURL", actualURL);
          interpreter.eval("source(tmpURL)");
          interpreter.unset("tmpURL");
        } catch (EvalError e) {
          if (LOGGER.isDebugEnabled()) LOGGER.debug("Could not source " + url + " ", e);
        }
    }
  }
コード例 #30
0
  @Test
  public void testCommonsLogging() {
    final org.apache.commons.logging.Log logger =
        org.apache.commons.logging.LogFactory.getLog(this.getClass());

    logger.trace("Foobar TRACE");
    AppenderForTests.hasNoLastEvent("at Trace level");
    assertFalse(logger.isTraceEnabled());

    logger.debug("Foobar DEBUG");
    AppenderForTests.hasNoLastEvent("at Debug level");
    assertFalse(logger.isDebugEnabled());

    logger.info("Foobar INFO");
    AppenderForTests.hasNoLastEvent("at Info level");
    assertFalse(logger.isInfoEnabled());

    logger.warn("Foobar WARN");
    AppenderForTests.hasLastEvent("at Warn level");
    assertTrue(logger.isWarnEnabled());

    logger.error("Foobar ERROR");
    AppenderForTests.hasLastEvent("at Error level");
    assertTrue(logger.isErrorEnabled());

    logger.fatal("Foobar FATAL");
    AppenderForTests.hasLastEvent("at Fatal level");
    assertTrue(logger.isFatalEnabled());
  }